PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

ChildAdded/ChildRemoved Events

ChildAdded/ChildRemoved Events

Jun 23 2018, 2:02 AM PST

Problem

You want to remove all parts coming into the Workspace and bring ones that have been removed back to the workspace.

Solution

Use the Instance/ChildAdded and Instance/ChildRemoved events.

Workspace.ChildAdded:connect(function(p)
	if p:IsA('BasePart') then
		p:Destroy()
	end
end)
 
Workspace.ChildRemoved:connect(function(p)
	if p:IsA('BasePart') then
		p.Parent = Workspace
	end
end)

Discussion

We simply connect both events, check if what’s leaving is a BasePart, and if so, apply the appropriate behavior. Instance/ChildAdded will fire when a new Instance is parented to the object (in this case Workspace). Note that they must be direct children in order to fire. So doing Instance.new('Part', Workspace) would make it fire, but Instance.new('Part', Workspace.Model) would not. The same with the Instance/ChildRemoved event.

Tags:
  • events
  • script