Question about events and cloning

Hello
-If I clone an object and there are connected functions to some of the events of this object, will these functions be connected also to the new object?
-Is there a way to detach all connected functions from a given event for a given object?

Thanks

To anwer the first question, no, connections are not cloned when an instance is cloned.

local Workspace = workspace

local function OnAncestryChanged(Child, Parent)
	print(Child.Name, Parent.Name)
end

local Part1 = Instance.new("Part")
Part1.Name = "Part1"
Part1.AncestryChanged:Connect(OnAncestryChanged)
local Part2 = Part1:Clone()
Part2.Name = "Part2"
Part1.Parent = Workspace
Part2.Parent = Workspace

The ‘AncestryChanged’ signal fires for the first part but not for the second.
image

To answer the second question, also no, there are no methods that retrieve an object’s connections, you need to cache (store) these your self.

local Workspace = workspace
local Part = Workspace.Part

local Connections = {} --Caches the part's 'Touched' connections.

table.insert(Connections, Part.Touched:Connect(function() print("Hello world!") end)) --Can insert connection directly.
local Connection = Part.Touched:Connect(function() warn("Hello world!") end) --Or indirectly via a variable reference.
table.insert(Connections, Connection)

task.wait(10)
for _, Connection in ipairs(Connections) do --Loop through the connections table.
	if Connection.Connected then Connection:Disconnect() end --Disconnect each connection.
end
1 Like

This can be easily tested, the answer is no.

I’m not sure if there’s an actual method for this, although you can store connections in variables and use the connection:Disconnect() method to detach the stored connection, example:

local connection 
connection = game:GetService("RunService").Heartbeat:Connect(function()
	print("Hello world!")
end)
task.wait(5)
connection:Disconnect()
1 Like

Answer to your second question is yes, but you need to cache all your connections and then call Disconnect() on them.