Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

unity3d

I have the following script which is attached to a game object and run when I click a button in the editor:

public void ClearChildren() {
    Debug.Log(transform.childCount);
    float i = 0;
    foreach (Transform child in transform) {
        i += 1;
        DestroyImmediate(child.gameObject);
    }
    Debug.Log(transform.childCount);
}

It shows that the original childCount is 13 and the final value is 6. Furthermore, if I print out all i each iteration I see the values 0-6, showing that the loop only runs 7 times, not 13 as expected.

How can I delete all the children such that the final value is 0? For reference, the children I'm trying to delete were automatically created by a vendor script. I'm also running this script in [ExecuteInEditMode] for what it's worth.

The following script has the same behavior; if the childCount starts at 4 then it ends at 2:

public void ClearChildren() {
    Debug.Log(transform.childCount);
    for (int i = 0; i < transform.childCount; i++) {
        Transform child = transform.GetChild(i);
        DestroyImmediate(child.gameObject);
    }
    Debug.Log(transform.childCount);
} 

If I try the following I get a runtime error pointing to the foreach line saying "InvalidCastException: Cannot cast from source type to destination type."

public void ClearChildren() {
    Debug.Log(transform.childCount);
    foreach ( GameObject child in transform) {
        DestroyImmediate(child);
    }
    Debug.Log(transform.childCount);
}
like image 302
max pleaner Avatar asked Sep 22 '17 07:09

max pleaner


1 Answers

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);
}
like image 159
Jim Yarbro Avatar answered Oct 13 '22 20:10

Jim Yarbro