renderStepped:Disconnect not working

The below function is meant to start a RenderStepped loop if the value passed through the first argument is true and disconnect the loop if it’s false, but it instead returns the following error when the function is called twice with the value passed as true the first time and false the second time:
“attempt to index nil with ‘Disconnect’”
Thanks in advance.

local function CameraLoop(startingLoop, Character)
	local renderStepped
	
	if startingLoop == true then
		renderStepped = RunService.RenderStepped:Connect(function()
			print(Character.Name)
		end)
	else
		renderStepped:Disconnect()

	end
end

In the case that startingLoop is false, renderStepped never gets assigned a value.

You’ll also want to move local renderStepped outside of the function, since if startingLoop is true, then it will just create new connections with no way to reference them.

local renderStepped

local function cameraLoop(startingLoop: boolean, character: Model)
	if startingLoop then
		renderStepped = RunService.RenderStepped:Connect(function()
			print(character)
		end)
	else
		if renderStepped then -- without this we would still have the same issue !!!
			renderStepped:Disconnect()
		end
	end
end

I also made your code a bit more consistent and added type annotations to the parameters so it’s a bit clearer what to pass.

2 Likes

The simplest solution is to make the variable that saves your connection (renderStepped) global from the cameraLoop point of view. Just remember that whenever you call cameraLoop with true, the next call must be with false, otherwise the function will behave strangely.

local renderStepped
local function CameraLoop(startingLoop, Character)
	if startingLoop == true then
		renderStepped = RunService.RenderStepped:Connect(function()
			print(Character.Name)
		end)
	else
		renderStepped:Disconnect()
	end
end
1 Like