Why is it multiplying instead of adding the change in value?

I am trying to create a rebirth system but I am having some issues with it. After the rebirth is over 1 whenever any points are gained it adds an insane amount instead of adding the change in value. I added a print function to see what the change in value was and it printed a bunch of numbers instead of 1 all multiplied by 2. How do I fix this?
Screen Shot 2021-11-25 at 9.01.29 AM

game.ReplicatedStorage.RebirthEvent.OnServerEvent:Connect(function(player)
	local rebirths = player.leaderstats.Rebirths
	local robux = player.leaderstats.Robux
	local CR = 0
	
	robux.Changed:Connect(function()
		local currentRobux = 0
		local robuxChanged = robux.Value - currentRobux
		if rebirths.Value >=1 then
			robux.Value = robux.Value + robuxChanged
			currentRobux = robux.Value
			print(robuxChanged)
		end
	end)
end)
1 Like

Assume my Robux changed to 1, which fires the event. The robuxChanged variable will be 1 because 1 - 0 = 1. This satisfies the if statement and then I’m adding whatever robuxChanged variable has to robux.Value, which results in 1 + 1 = 2.

Your problem is that you’re basically multiplying robux.Value by 2. Let’s break it down.

local robuxChanged = robux.Value - currentRobux

Let’s get rid of currentRobux because you’re setting it to 0 right before that.

robux.Value = robux.Value + robuxChanged

And, using the previous information, this can be simplified as

robux.Value = robux.Value + robux.Value

which is what’s giving you the error. You’re essentially multiplying by 2 with every time the function fires, and you just didn’t notice.

1 Like

This is also because if the server is fired multiple times this would result in the callback function being connected to the robux.Changed event multiple times, you need to disconnect old connections before creating new ones.

2 Likes

How would I disconnect the old connection?

I’m assuming you want to run the function only once so you can use Wait instead of Connect:

robux.Changed:Wait()
-- run code