Function doesn't always disconnect

I current have this code in a localscript and it makes your camera shake. It starts shaking and should shake less and less as the function runs more. When shakeMax is lower than 1 it should disconnect the function and therefore stop the shaking. However, it doesnt always disconnect, sometimes it keeps printing ‘done shaking’ for every time the function runs. What causes this and how do i solve it?

local shakeMin = 0
local shakeMax = 400
local drop = 0.21
	
loop = game:GetService('RunService').RenderStepped:connect(function()
	if shakeMax > 1 then
		game.Players.LocalPlayer.Character.Humanoid.CameraOffset = Vector3.new(math.random(shakeMin, shakeMax)/1000, math.random(shakeMin, shakeMax)/1000, math.random(shakeMin, shakeMax)/1000)
		shakeMax = shakeMax - drop
	else
		loop:Disconnect()	
		print('done shaking')
	end	
end)

I’d recommend that you use BindToRenderStep as you can utilise UnbindFromRenderStep and the priority argument too.

For example:

local RunService = game:GetService("RunService")

RunService:BindToRenderStep(
    "CameraShake", --// Bind name
    Enum.RenderPriority.Camera.Value, --// Priority
    function() --// Function to run
        --// Code
        RunService:UnbindFromRenderStep("CameraShake") --// Unbind the function
    end
)

If you want to keep using the RenderStepped event, try defining but not assinging loop before assigning to to the connection.
ie.

local loop 
loop = --// code
4 Likes