Will this cause a memory leak?

This is a toggle function that creates and destroys an event connection. I am doing this because the object that the event is tied to won’t always exists, so I need to make the connection when it’s created, and disconnect when the object is deleted.

local Connection

function ToggleMobileInput(Toggle)
	if Toggle then
		Connection = ActiveTalkPrompt:WaitForChild("UI"):WaitForChild("Button").MouseButton1Click:Connect(function()
			print("bonejuice")
		end)
	else
		Connection:Disconnect()
	end
end

Will this method cause a memory leak? Or will it be alright.

1 Like

You would be overriding Connection if you were to call that function with Toggle as true twice in a row. So, you should nil check and Disconnect even when toggling on.

1 Like

So is it alright otherwise? Just changed it.

EDIT: I’ll take that as a yes. Thanks.

If your object is deleted, presumably with Destroy, all the connections of that object will be disconnected automatically, so there’s no need to Disconnect the connections yourself.

I would be more concerned about this part.
Maybe store variables inside the function to make it look better.