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.
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.
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.