How would I delete everything inside a certain instance except for one thing?

Hi there,

Sorry if the title is kind of vague, but what I’m trying to find out is what is the best way to clear all the children except one thing. What I thought was to loop through all the children of an instance and delete it if the name is not ____. Is there any better ways to do this or the method I stated is the best or only way?

Thanks for the help.

There are more ways depending on what you are doing. You do the IsA(“”) Command if one thing is unique in the Instances.

1 Like

I’d suggest using a pairs loop and an if statement to see if the select part == the part you don’t want to delete.

It’d look a bit like this:

for i, v in pairs(part:GetChildren()) do

  if v ~= BADPART then
    game:GetService("Debris"):AddItem(v, 0.1)
  end

end
3 Likes

Got it. Thanks for the help. :slight_smile:

2 Likes

It would be much more efficient to just delete the part. E.g.

for _, part in pairs(part:GetChildren()) do -- loop through the parts one at a time
  if part.Name ~= 'name here' then -- continue if the name of the part isn't equal to the 'name here' string. The ~= sign means not equal
    part:Destroy() -- destroy the part
  end
end
5 Likes

The above solutions work very well, but I’ll be chipping in with a few alternate solutions, just so no option goes unexplored.
I propose to to parent the thing somewhere else, :ClearAllChildren the instance and parent it back:

oneThing.Parent = nil -- or certainInstance.Parent
certainInstance:ClearAllChildren()
oneThing.Parent = certainInstance

Another way to do it is to create another equivalent certainInstance from scratch (cloning it would clone everything in it), parent oneThing to it and destroy the original.
The drawback is that it involves changing the Parent of oneThing, which often has side-effects such as breaking joints or tripping change events. I don’t recommend actually doing this.

What if there were more than one part?
You would have to copy the script for every part.

Just use one script to loop through lots of parts.

If there was a full scale titanic (No references just an example) Then you would have to copy the same line Over and Over again.

No you don’t. Just have one script that loops through all the parts of the titanic just like how the script I put before loops through the children of a part.

Example

if part.Name ~= ‘name here’ then

if part.Name ~= ‘name here’ then

if part.Name ~= ‘name here’ then

if part.Name ~= ‘name here’ then

if part.Name ~= ‘name here’ then

The OP asked how to check if the name ~= to something and if it isn’t delete it. What are you trying to achieve?