Transform.childCount and Transform.GetChild behavior
I tried to write a function which deletes the object's children. I've since found another solution for that problem, but I don't understand why the method I wrote doesn't work. Here it is:
private void destroyAllChildren() {
while (transform.childCount > 0) {
print("destroy!");
Destroy(transform.GetChild(0).gameObject);
}
}
Running the unity editor with this function called in Start() causes the editor to crash. I believe the person who asked this question http://answers.unity3d.com/questions/1073544/transformchildcount-question.html had pretty much the same logic issue, but there wasn't any explanation as to why there was an issue.
tl;dr, why is there an issue?
I responded to your comment on the other question - their problem had to do with using the Invoke function with a delay. Are you using Invoke?
Answer by Dave-Carlile · Dec 30, 2015 at 08:50 PM
When you Destroy a gameobject it isn't actually destroyed until later in the game loop. Quoting the documentation:
Actual object destruction is always delayed until after the current Update loop, but will always be done before rendering.
So your loop is attempting to destroy the same object multiple times because it isn't actually removed from the child collection until later.
I'm surprised that you example causes the editor to crash though. I would expect a message indicating the object has already been destroyed. What happens when you pass i
instead of 0 to GetChild?
Thanks for the explanation. I meant to post a previous version of the function where I use a while loop, so I modified my question to include that one.
Yes, that would cause an infinite loop because childCount
never decreases since the object isn't destroyed until later, and later can never happen because of your infinite loop. :)
Your answer
Follow this Question
Related Questions
Iterating through children causes InvalidCastException 1 Answer
reset a GameObject parents childs to 0 if a item has changed its parent 2 Answers
how to access the Transform of a moving child object? 1 Answer
Looking through all the children doesn't work 1 Answer
Destroyng all childs of an object 1 Answer