How to check the value from a NumberValue

55 Views Asked by At

I'm making a game and I want to make a generator system. You have to turn on 5 generators to win. Everytime a generator is turned on I increase a NumberValue + 1. My problem is: I don't know how a other script can check if the Value of the NumberValue is 5.


I tried: if NumberValue.Value == 5 then print("It worked!")

I also tried to put the script into SeverScriptService, Workspace or ReplicatedsStorage but it didn't work :(

2

There are 2 best solutions below

0
Quanty On

Have you defined "NumberValue" yet? Have you put it in a forever loop with a task.wait(0) line? normally this script would work in workspace

local NumberValue = workspace.Value --define NumberValue (replace it with where the number value is)

while task.wait(0) do --repeat forever but wait a frame each time
    if NumberValue.Value == 5 then
        print("It worked!")
    end
end
0
Kylaaa On

You're on the right track but the issue is that your code executes once and then never checks again.

A good way to handle this is to have your script listen for the NumberValue's Changed signal. Whenever the Value changes, it will trigger the function. So try something like this :

-- find the NumberValue Instance
local NumberValue = game.Workspace.NumberValue

-- listen for when it changes
NumberValue.Changed:Connect(function(newValue)
    print("NumberValue update to", newValue)
    if newValue == 5 then
        print("It worked!")
    end
end)

Then, whenever something changes the Value, you should see this message appear.

Be careful though, if this code is in a Script, then the code that sets the NumberValue.Value must also be in a Script for this to work.