If I connect, a function to the property, e.g. Touched
of an object:
MyPart.Touched:Connect(function(OtherPart)
...
end)
… and at some point, I destroy this object: MyPart:Destroy()
…
… is this connection automatically removed by the Engine?
Or should I worry about manually removing this connection before destroying the object?
2 Likes
Zirkonir
(Zirkonir)
June 10, 2022, 3:24pm
#2
The function will not be ‘removed’, so to speak, however there will be nothing to send the Touched
signal, so you won’t need to worry about it.
2 Likes
I see, but technically speaking, if I have 1000 objects created and then destroyed, will there be 1000 functions taking up memory or processing, somehow hurting the game’s performance?
kaan650
(Kaan)
June 10, 2022, 3:29pm
#4
When a part gets destroyed, all event connections to that part are also disconnected automatically
3 Likes
Forummer
(Forummer)
June 10, 2022, 3:54pm
#5
Only the one lambda function is defined.
function self.blah()
end
Is syntactic sugar for:
self.blah = function()
end
Unlike tables, functions are mutable and do not change state (cannot be used to track state). In this instance, the ‘blah’ key/field for each of the 10 ‘self’ tables points to the same lambda function, it does not need to be redefined 10 times as it can be held in memory and it will always contain the same body of code (regardless of the table it belongs to). This is just one of the many memory optimisations undert…
Additionally, a destroyed instances connections are automatically disconnected.
2 Likes
If connections gets spammed, there will be so much lag…
If there is another event that can still fire (like stringValue.Changed) and I connected a function to it, how do I “disconnect” that, as soon as the MyPart (in this case) is destroyed?
Zirkonir
(Zirkonir)
October 21, 2024, 6:37pm
#8
Store the connections as a variable then call :Disconnect()
, for example:
local connection: RBXScriptConnection = <StringValue>.Changed:Connect(function(): nil
-- Blah blah
return nil
end)
<BasePart>.Destroying:Once(function(): nil
connection:Disconnect()
print("Disconnected the connection.")
end)