I’ve had this question for a long time, what is :Diconnect()? When is it used? Why is it necessary? I’ve heard its something to do with memory leaks and i’ve seen it used with Runservice.Renderstepped
Any help is appreciated.
I’ve had this question for a long time, what is :Diconnect()? When is it used? Why is it necessary? I’ve heard its something to do with memory leaks and i’ve seen it used with Runservice.Renderstepped
Any help is appreciated.
Disconnects a rbxeventsignal. Which is why you should use it when renderstepped loops is not needed anymore or similar functions.
like this
local con -- this is the connection, you have to add it before hand
local part = script.Parent
con = part.Touched:Connect(function() -- set connection to the event
print('touched') -- wont fire 2nd time after being touched
con:Disconnect() -- disconnect the connection making the event not fire
end)
It disconnects RBXScriptSignal
s which stop them from running. If you hook up a RBXScriptSignal
to an instance, such as Part.Touched
, you don’t have to disconnect it if the part is destroyed. Otherwise, you’d have to disconnect them manually (or if you don’t need it anymore).
lets say you wanna do something like, have a touch event run for a certain amount of time
part.Touched:Connect(function()
print'how dare you touch me'
end)
wait(10)
--i dont want it to trigger when its touched anymore after 10 seconds
so you do
local connection
connection = part.Touched:Connect(function()
print'how dare you touch me'
end)
wait(10)
connection:Disconnect()
:Disconnect
stops an event from listening for the next time it fires, specifically RBXScriptSignal
.
Why is this useful?
Well, when u have a game with lots of events, if u don’t disconnect them after u no longer need it, it will continue to listen for it and clutter up the memory.
Thats why most scripters use Janitor
or Maid
to manage their events, as they automatically cleans up all of the events, when the Janitor/Maid
is destroyed.
One grt example, is RenderStepped
, it fires every 1/60th of a frame, and if u don’t disconnect it, it will continue firing everytime, regardless of whther u need it or not.
So all in all I’d recommend u to use Janitor
or other utility rather than disconnecting them manually, which can b tedious.
Thanks, I was overcomplicating it in my head but now I understand.
If u found a solution satisfactory, pls mark it as solution as it would help others with the same questions.
Additional information if necessary.