A very open question, but again as the title says, when should I be disconnecting events? I’ve never really used the :Disconnect
function all that much, but I know that I should be since my games could be suffering from memory leaks.
Probably doesn’t have one definitive answer, but it might help me in the long run to know.
If you’re not using it than just disconnect the event listener. It just depends on the application as some things might never be considered unused while other things might only be used when a certain minigame or map is being used.
:Disconnect only really needs to be used if you’re not using the event anymore / you dont want to use it, and the object STILL exists.
Also, connections are automatically disconnected when the object in question is destroyed (ex: clickdetector gets destroyed → no more .MouseClick)
Hey!
Now, disconnecting events is a pretty interesting topic since you don’t see many people use it even though it can be used for many useful things, for example only make something available for a specific time.
You would also only need to disconnect an event if you really don’t need it anymore. This for example is, if you’re trying to only make something happen for 60 seconds.
Then you would do something like this:
local connection
connection = RemoteEvent:OnServerEvent:Connect(function(player)
-- Code here
end)
wait(60)
connection:Disconnect()
Note, if you delete any object with a event added to it, it gets disconnected automatically. For example if you would delete the RemoteEvent | Roblox Creator Documentation of the example above, the connection is already disconnected automatically.
Now, disconnecting events is not really as necessary. If you want to save as many ressources as possible, always disconnect your events as it saves some ressources of the roblox servers.
If you’re more interested into Handling Events, the Handling Events article can be really helpful for you.
Cheers