I have code that runs for each character in my level on RenderStepped.
When the character dies, I have the script destroy itself.
Do I need to disconnect from RenderStepped before calling script:Destroy() or will Roblox do this for me?
In other words, does the code below leak memory?
3 Likes
The Roblox game engine will clean up event connections for you when your script is deleted. Memory will not be leaked from dead connections.
It’s weird. The Connected property doesn’t turn false, but dead connections are garbage-collected.
Code
-- ---------------
-- | ScriptA |
-- ---------------
_G.MyTestConnection = workspace.DescendantAdded:Connect(function(...)
-- Do something.
end)
-- ---------------
-- | ScriptB |
-- ---------------
wait(1)
-- Disable test
print("Doing disable test.")
wait(1)
script.Parent.ScriptA.Disabled = true
print("- Disabled ScriptA.")
wait(1)
print("- Still connected? -", _G.MyTestConnection.Connected) -- Oddly, it returns true.
-- Garbage collect test.
print("Doing garbage collect test.")
local t = setmetatable({}, {__mode = "v"}) -- So values can be garbage collected
t[1] = _G.MyTestConnection
_G.MyTestConnection = nil
wait(10) -- To let a garbage collect cycle happen.
print("- Garbage collected? -", t[1] == nil)
Doing disable test.
Disabled ScriptA.
Still connected? - true
Doing garbage collect test.
Garbage collected? - true
2 Likes
sjr04
(uep)
May 30, 2020, 9:11pm
3
When a script is destroyed the connections created inside it are as well.
In ServerScriptService I had this script
game:GetService("Workspace").ChildAdded:Connect(print)
But when I delete the script:
it stops printing.
You should be fine.
Elocore
(Elocore)
May 30, 2020, 9:12pm
4
No it doesn’t it will only clean up if the script is deleted or disabled. If your not destroying the script then you will have to Disconnect() them yourself if you dont need them anymore. I highly recommend you do this because having event listeners you don’t need will take a performance toll
1 Like