I have a number value that I subtract a given number from when a mouse is clicked and just automatically. The problem is, though, that occasionally I subtract a number more than once very close in time to each other in two different scripts. The value, instead of combining both numbers that are being subtracted, only subtracts one of the numbers. Why is this happening?
Script #1
local value = game.Workspace.NumberValue.Value -- let's assume value is 30 local randomNumber = 5 function Down(mouse) -- assuming the mouse is clicked very close to the time before randomNumberTwo is subtracted from the value in script #2 and very close to the time after randomNumberTwo is subtracted value = value - randomNumber print(value) end function Selected(mouse) mouse.Button1Down:connect(function() Down(mouse) end end -- Output = 25
Script #2
local randomNumberTwo = 10 local value = game.Workspace.NumberValue.Value -- since only 1 mouse click has occured, the value should now be 25 wait(3) value = value - randomNumberTwo print(value) -- Output = 20 | the output should be 15, but it's not
This is a great question! It highlights one of the subtleties and pitfalls of working with any sort of Value
Instance.
As you probably understand, the ROBLOX game
hierarchy is composed of Services
(like Players, Workspace, Lighting, and ReplicatedStorage) and other Instances
(like Part, Humanoid, and StringValue).
Inside a Script, you can have a variable that refers to an Instance or you can have a variable that refers to a certain value (a value like 5, "hello", {'a','b','c'}, or -2.7843).
Let us analyse the first line of Script #1
local value = game.Workspace.NumberValue.Value
The above is like saying "store the numerical value of 'NumberValue' in the variable called 'value'.
Now consider this:
local numberValue = game.Workspace.NumberValue
The above is like saying "store a reference to the Instance
called "NumberValue"
in the workspace.
So, the problem is that at the beginning of your scripts, you are taking just the numerical value from the Instance
in the workspace, rather than a reference to that Instance
. This means that the value you get at the end will only be a manipulation of the value that the "NumberValue"
starts with.
This seems like a good explanation: Both scripts start with 30 as their value, the first one takes 5, leaving 25. The second script takes 10 (from 30), leaving 20.
Here are your scripts re-written to accommodate this slight change:
local numberValue = game.Workspace.NumberValue local randomNumber = 5 function Down(mouse) numberValue.Value = numberValue.Value - randomNumber print(numberValue.Value) end function Selected(mouse) mouse.Button1Down:connect(function() Down(mouse) end) end
local randomNumberTwo = 10 local numberValue = game.Workspace.NumberValue wait(3) numberValue.Value = numberValue.Value - randomNumberTwo print(numberValue.Value)