Will I have to manually remove functions connected to an object when it is destroyed?

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

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?

When a part gets destroyed, all event connections to that part are also disconnected automatically

3 Likes

Only the one lambda function is defined.

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?

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)