Subtracting 0.4 then adding 0.4 back to a variable returns incorrect number

What this needs to do is make power go by quicker if doors are closed, measured by Power Tick. Ideally, when a door’s closed value is set to true, it subtracts a set integer from powertick (In this case, 0.4).

What happens is, when leftDoorStatus.Value is set to true, powertick returns 4.4. Wonderful!. But when the code to add 0.4 back to it is ran, it returns 5.2 instead, and I can’t seem to figure out why. If you guys can help, it would be much appreciated!

Here is the code:

local totalPower = 100
local incrementedPower = 0.4

local leftDoorStatus = game.ReplicatedStorage.Values.Left
local rightDoorStatus = game.ReplicatedStorage.Values.Right

while wait(powerTick) do
	
	game.ReplicatedStorage.Events.UpdatePower:FireAllClients(totalPower)
	totalPower = totalPower - 1
	print(totalPower)
	leftDoorStatus:GetPropertyChangedSignal("Value"):Connect(function()
		if leftDoorStatus.Value == true then
			powerTick = powerTick - incrementedPower
		elseif leftDoorStatus.Value == false then
			powerTick = powerTick + incrementedPower
		end
	end)
	print(powerTick)
end

The problem is that you are creating an event inside a loop. This causes a new event to be created on each iteration, resulting in the wrong behavior. Simply create the event outside the loop.

leftDoorStatus:GetPropertyChangedSignal("Value"):Connect(function()
	if leftDoorStatus.Value == true then
		powerTick = powerTick - incrementedPower
	elseif leftDoorStatus.Value == false then
		powerTick = powerTick + incrementedPower
	end
end)

while wait(powerTick) do

	game.ReplicatedStorage.Events.UpdatePower:FireAllClients(totalPower)
	totalPower = totalPower - 1
	print(totalPower)

	print(powerTick)
end

1 Like

Thank you! This solution worked. I thought that events created outside the loop wouldnt run as the code is looping only through the loop block. Nevertheless, thanks for your help!