Delete children of GameObjects in Unity

Published

I was working on procedural placement for the upcoming beta of my game Dungeons of Azoya, and needed to clear intermediary results while developping, which meant deleting all instantiated game object. Btw, I’ll be sharing an improved version of my GameObjectDrawPool script, along with an algorithm for procedural placement of object soon.

Anyways, to clear all these children, the easiest method I could think of is to set all instantiated game objects as a child of a given target object in the generation algorithm, which then allows me to simply iterate on this parent gameobject and delete all children.

The process is simple, with 2 caveats:

  • I’m running this code while in Editor mode, not play mode, so you need to use “DestroyImmediate” instead of “Destroy”, and this function must be used on game objects, not transforms.
  • I’m unsure how the indices of the list of children are handled since we are deleting elements, so I am using a decrementing loop to ensure I don’t access invalid indices.

Considering all this, the code is pretty simple:

public class ChildrenCleaner: MonoBehaviour {
  public Transform mTargetObject;

  public void CleanChildren() {
    int nbChildren = mTargetObject.childCount;

    for (int i = nbChildren - 1; i >= 0; i--) {
        DestroyImmediate(mTargetObject.GetChild(i).gameObject);
    }
  }

}