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);
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With