Can someone give me some examples on how ChildAdded and ChildRemoved work?

I tried self-learning how ChildAdded and ChildRemoved work, but I failed

Can you guys give me some examples on how they work?

3 Likes

Attaching a ChildAdded event to an object would mean that the event will fire if another object is parented onto the object with the event.

The same goes for ChildRemoved, but the opposite must be satisfied, aka an object would be removed from the object for ChildRemoved to be fired.

-- a folder just for the example
local folder = Instance.new("Folder")
folder.Parent = workspace

-- this will fire when an instance is added a child to 'folder'
folder.ChildAdded:Connect(function(child)
   print(`Child added {child.Name}`)
end)

-- this will fire when an instance is removed from 'folder'
folder.ChildRemoved:Connect(function(child)
   print(`Child removed {child.Name}`)
end)

local part = Instance.new("Part")
part.Parent = folder -- Fires the 'Folder.ChildAdded' event since a new child was added

task.wait(3)
part.Parent = workspace -- Fires the 'Folder.ChildRemoved' event since the child was removed
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.