How to wait till a Number Value changes?

How could I make a script that takes a Number Value (that is equal to 0) and waits till it changes to something different than 0 to print a message? If the value doesn’t change within 15 seconds, it kicks you out of the game.

3 Likes

It’s simple. Just connect to the “Changed” function of the NumberValue.

local numValueRef = Instance.new("NumberValue")

numValueRef.Changed:Connect(function(value)
    print(value)
end)

I don’t know about you, but you probably should’ve looked at the documentation of NumberValue’s. On a different note, hope this helps and good luck!

3 Likes

Thanks! I forgot to check the documentation sorry lol

1 Like

You can create a while loop (under a coroutine or spawn function), to create a 15 second timer. Make sure you are using a server script for this, as you should only kick the player on the server.

Here is your code example:

local timer = 0 -- timer
local NumberVal = -- state where your 'NumberValue' is currently located
local changed = false -- will be set to 'false' if 'NumberValue' hasn't changed, and set to 'true' if 'NumberValue' has changed

coroutine.wrap(function() -- any code under this function will not yield the thread
	while (not changed) do -- while 'changed' is currently false
		if timer == 15 then -- if timer limit is reached
			player:Kick() -- I'm not sure how you are getting the player, so remember to have a player variable before running this
			break
		else
			timer += 1 -- adds '1' to the 'timer' variable every second
		end

		task.wait(1) -- waits 1 second before rerunning the loop
	end
end)()

NumberVal:GetPropertyChangedSignal("Value"):Connect(function() --[[ you can also use the 'Changed' event, no big difference, 
	however, the 'GetPropertyChangedSignal' can basically run for any other instance with an 
	existing property you state in the quotes. ]]

	if NumberVal.Value ~= 0 then -- if the value is not '0'
		changed = true -- set 'changed' to true
		timer = 0 -- reset timer
		print(NumberVal.Value)
	end
end)
1 Like

Hello, have you tried using my implementation to what you were trying to achieve in my post above? It has been a few days without any response, so I was just wondering.

1 Like

I tried, it works but the script is really long and I managed to make it shorter. Thanks for the help tho!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.