How to loop through and destroy all children of a game object in Unity?

Are all the children direct childrens of your parent object?

I believe the foreach(Transform child in transform) will only loop through the children that are in the first level after the parent. So if there are objects that are childrens of a child of a parent they wont be looped. Parent -> Child1 -> Child2 (child of Child1). Hope its undestandable what i mean.

To also get the childrens in second level and forth i would use:

Transform[] allChildren = GetComponentsInChildren<Transform>(true);

And then loop through this list to destroy them (As pointed out by Programmer):

The problem is that you are trying to remove the Object in the for loop while accessing them.


The problem is that you are trying to remove the Object in the for loop while accessing them.

Here is what you should do:

  1. Find all Child objects and store them in an array

  2. Destroy them in another loop

     public void ClearChildren()
     {
         Debug.Log(transform.childCount);
         int i = 0;
    
         //Array to hold all child obj
         GameObject[] allChildren = new GameObject[transform.childCount];
    
         //Find all child obj and store to that array
         foreach (Transform child in transform)
         {
             allChildren[i] = child.gameObject;
             i += 1;
         }
    
         //Now destroy them
         foreach (GameObject child in allChildren)
         {
             DestroyImmediate(child.gameObject);
         }
    
         Debug.Log(transform.childCount);
     }
    

The other solutions here seem over-engineered. I wanted something with a smaller code footprint. This destroys the immediate children of an object, and all of their descendents.

while (transform.childCount > 0) {
    DestroyImmediate(transform.GetChild(0).gameObject);
}

Tags:

C#

Unity3D