RenderStepped not disconnecting

Hello, I have a building system within my game which includes a RenderStepped event binded to n variable named “deleteConnection”. deleteConnection is used to show a selection box around any objects that the mouse hovers over. My issue is when my cancel function, which runs :Disconnect(), continues to run for some reason.

(I’ve removed any extra code so its easier to read)

delete function:

function BuildHandler.delete()
	deleteConnection = RunService.RenderStepped:Connect(function()
		local boundingBox = mouse.target.Parent.Parent:FindFirstChild("BoundingBox")
		if lastTarget ~= nil and lastTarget ~= boundingBox then
			--removes some selection box effect
		end
		if boundingBox then
			--does some selection box effect
			lastTarget = boundingBox
		end
	end)
end

cancel function:

function BuildHandler.cancel()
	if buildConnection and item then
		buildConnection:Disconnect() --this works fine to cancel building
		item:Destroy()
		item = nil
	end
	if deleteConnection then
		deleteConnection:Disconnect()
		print(deleteConnection) --still prints connection
		--removes selection box effect if its still visible
	end
end

If anyone can inform me why this is happening, that would be great. Thanks.

I understand why it still prints the connection object; because you still have reference to it so it’ll be there until all references have been removed.

e.g:

--//disconnect listener
 deleteConnection = nil

With that said, maybe add a print in the area where you define the event connection for deleteConnection to see if there’s a chance it’s getting called again repeatedly.

Thanks, actually was a mistake by me. My function was binded to keybind with ContextActionService and I forgot to check ther UserInputState. Simply adding a check for it solved this. Thanks again.

1 Like