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

Using DescendantAdded Events

Using DescendantAdded Events

Jun 29 2018, 4:52 PM PST

Problem

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).

Solution

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)

Discussion

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