Destroy all objects that have the name x

I didnt know but, is it possible to delete every single object that has the name (Insert name)?
Lets say I instantiate a tree prefab and give it the name “Tree” and I repeat this 3 times, how could I delete all objects that have the name “Tree”? Hope this makes since.

Use FindObjectsOfType() to get all Transforms.

Then iterate those, and from each one access the .gameObject shortcut to do your thing.

1 Like

A pedantic side note: transform.name will also contain the name of the GameObject.

2 Likes

Thanks

Better practice would be to avoid using names of objects at all. You said you instantiated them. Did your mom ever say to you “I brought you into this world, I can take you out of it”? Same thing applies here. Keep track of all the trees you spawned and you can destroy them all easily and efficiently.

List<GameObject> trees = new List<GameObject>();

void SpawnTree() {
  GameObject tree = Instantiate(treePrefab);
  trees.Add(tree);
}

void DestroyAllTrees() {
  foreach (var tree in trees) {
    Destroy(tree);
  }
  trees.Clear();
}
2 Likes

I would never recommend using the Find method of unity except you dont have another chance. You need to keep in mind that the Find method runs over all objects in your script.
So if your project increases, and lets make an example of 10 000 GameObjects, you are running through a list of all those 10 000 GameObjects to find a name. And lets say you use your Find method 10 times in Update (example for find tree, find rock, find …), you efficiently search through 100 000 GameObjects in a single Update call.

So i highly recommend the solution above!