PcoWSkbVqDnWTu_dm2ix

Using DescendantAdded Events

Using DescendantAdded Events

Jun 14 2019, 4:47 PM PST

You want to use Changed Events, but have it fire when you add it to a descendant too (e.g. Instance.new('Part', Workspace) would fire and Instance.new('Part', Workspace.Model) would fire, but Instance.new('Part', game.Players) would not).

Use the DescendantAdded and DescendantRemoving events.

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

We do the exact same thing as last time except we change the events. The Descendant events fire on direct children, and descendants of the object.

There is also a function called IsDescendantOf which will check if something is a descendant of another object.

local part = Instance.new('Part')
part.Parent = workspace
  • print(part:IsDescendantOf(game)) --> true
  • print(part:IsDescendantOf(Workspace)) --> true
  • print(Part:IsDescendantOf(game.Lighting)) --> false
Tags:
  • events
  • coding