Number effect bug

local function interpolate(a, b, lab)
	local diff = b - a
	print(diff)
	if diff > 5 then
		for t=0, 1, 1/30 do
			
				local money = a + (b-5-a)*t
				
				lab.Text = tostring(math.round(money))
				task.wait()
				
			
		end
		task.wait(0.02)
		lab.Text = tostring(math.round(b-4))
			
		task.wait(0.05)
		lab.Text = tostring(math.round(b-3))
		task.wait(0.1)
		lab.Text = tostring(math.round(b-2))
		task.wait(0.15)
		lab.Text = tostring(math.round(b-1))
		task.wait(0.2)
		lab.Text = tostring(b)
	elseif diff < -5 then
		for t=0, 1, 1/30 do

			local money = a + (b-5-a)*t
			
			lab.Text = tostring(math.round(money))
			task.wait()


		end
		task.wait(0.02)
		lab.Text = tostring(math.round(b+4))

		task.wait(0.05)
		lab.Text = tostring(math.round(b+3))
		task.wait(0.1)
		lab.Text = tostring(math.round(b+2))
		task.wait(0.15)
		lab.Text = tostring(math.round(b+1))
		task.wait(0.2)
		lab.Text = tostring(b)
	else
		for t=0, 1, 1/60 do

			local money = a + (b-a)*t
			
			lab.Text = tostring(math.round(money))
			task.wait()


		end
	end
end

FIrst one is good, second one is the bug

TLDR when the stat value gets changed too quickly, causes the function to bug

Instead of calling the function three separate times, have you tried just calling it once with the overall change?

yeah, I could, but the issue is, this is just the egg system, in other parts of the game like farming, they gain/lose the currency faster in faster than 0.5 seconds(the time the effect takes)

Here’s my method. This will allow you to change the value using the setGoal() function and it will always smoothly reach the goal value.

I haven’t tested any of this code I just wrote it in devforum.

local smoothness = 0.8 -- Affects transition speed, lower is faster (0 - 1)

local rsConnection = nil
local goal = 0
local current = 0

-- Smoothly updates the text.
function step()
	-- Update current variable based on smoothness.
	current = goal * (1 - smoothness) + current * smoothness
	
	if math.abs(current - goal) < 1 then -- Close to goal.
		current = goal -- Set to goal.
		-- Stop updater.
		rsConnection:Disconnect()
		rsConnection = nil
	end
	
	-- Update text.
	lab.Text = tostring(math.round(current))
end


-- Sets the goal value, starts updater.
function setGoal(v)
	goal = v
	if not rsConnection then -- Updater isn't running, start it.
		rsConnection = game:GetService("RunService").RenderStepped:Connect(step)
	end
end