Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to remove an object's children?

I was making a part that would remove a player's tools when walking on it. But I don't know how to remove an object's children. I could try

player.Backpack.sword:Destroy()

But that's only targeting a specific object, "sword". I also tried

player.Backpack:GetChildren()Destroy()

But that didn't work either. How would I remove an object's children?

1 answer

✓ Accepted answer

Iterate through the table that GetChildren gives you and delete each instance. Destroy cant use the information in a table, only on single instances. Like so:

local Children = player.Backpack:GetChildren()

for i=1,#Children do
	Children[i]:Destroy()
end

Now this is quite complicated so let me explain. First you store the table of children in a variable so it can be properly read later in the script.

Next create a for loop that executes once for every child in the backpack. This is done by using #, an operator that counts how many items are in a table that it is in front of, so now it will go up from the first number (1) to whatever number follows it (However many items are in the table). i (Or whatever variable name you want, it doesn't need to be the letter i) can be read later in the script and it will tell you which loop it is currently on.

Next destroy each child, this is done by getting each item in the table and destroying it. This is coded by putting a number at the end of the table with square brackets around it, if you use i instead of a number it sorts itself out.

5 comments

0

Thanks! but there still is one problem... If the tool is activated while stepping on the part it doesn't remove it. Do you think there is a way to fix this?

0

by activated do you mean idle, not being used, but just sitting in your hands.

0

yes

0

Its probably because the item is moved somewhere else while its equipped, likely into the character. If so you can use player.Character to get the character, then delete it from there.

0

oohh ok

This discussion is preserved as it was. New answers, comments, and votes are closed.