Does I need use disconnect when I delete button?

I have button with connected on it function:

local Button = ScreenGui.SomeRandomButton
local Connections = {}
Connections[#Connections + 1] = Button.MouseButton1Click:Connect(function()
–something
end)

Should I disconnect this function if Button was destroyed?

Button:Destroy()

3 Likes

No, because when the instance is destroyed, it disconnects all connections.

1 Like
local Connection
local Debris = game:GetService("Debris")

Connection = Button.MouseButton1Click:Connect(function()
    -- Something
end)

Connection:Disconnect()
Debris:AddItem(Button, 0.1)

That should work for ya! :slightly_smiling_face:

1 Like

An instances connections are disconnected when that instance is destroyed but you’ll need to nil the connection’s table index otherwise the reference to that connection object will still exist (and won’t be garbage collected).

local button = script.Parent

local connections = {}

local mouseClickConnection
mouseClickConnection = button.MouseButton1Click:Connect(function()
	print("Clicked!")
end)
table.insert(connections, mouseClickConnection)

button.AncestryChanged:Connect(function(child, parent)
	if parent == nil then
		connections[mouseClickConnection] = nil
	end
end)
5 Likes

What happens when I destroy the script itself instead of the instance ? Will the connections be disconnected automatically ?

No, script will continue running.

Then how should I stop the connection if the script is destroyed ?

No it wont. The script will stop running when destroyed and the connections will no longer be active and should be garbage collected. You can test out the behavior by adding this script inside a part:

script.Parent.Touched:Connect(function(hit)
	print(hit)
end)

task.wait(3)

script:Destroy()
1 Like

If the connection isn’t saved, I assume the connection object would get GC’d because nothing is pointing to it. Is this correct?