using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class TESTFORUNITY : MonoBehaviour {
void Start () {
for (int x = 0; x < 4; x++)
{
GameObject GO = new GameObject("obj"+x);
GO.transform.SetParent(transform);
GO.AddComponent<RectTransform>();
}
Debug.LogWarning(transform.childCount);
while (transform.childCount > 0) Destroy (transform.GetChild(0).gameObject);
}
}
Drop that code onto anything in the canvas…
If you comment out the last line the debug statement prints 4.
Run that last line of code and Unity will go into an infinite loop…
public class TESTFORUNITY : MonoBehaviour {
void Start () {
for (int x = 0; x < 4; x++)
{
GameObject GO = new GameObject("obj"+x);
GO.transform.SetParent(transform);
GO.AddComponent<RectTransform>();
}
Debug.LogWarning(transform.childCount);
for( int i = transform.childCount-1; i >= 0; i--) Destroy (transform.GetChild(i).gameObject);
Debug.LogWarning(transform.childCount);
}
}
Looking in the Hierarchy you will see that all objects are successfully destroyed…
Note how the childCount is still stuck saying there is 4…
This suggests to me that the GameObject is only destroyed at the end of the frame but since the loop is still in the same frame, the object is not destroyed yet and thus childCount will never decrease… There if your infinite loop right there.
This bit me in the ass a few times but now that I can reproduce (and I think) explain it, I guess my question has become more of a tutorial for something to look out for…
When I posted that first sample I was really baffled, but with the second example, when I saw that childCount was not updated it all became clear…
Thanks, though, for the document reference. I was looking in the Transform for the answer, not in the GameObject. But… I got there in the end so all is well now
There is a DestroyImmediate function if you really need the objext to die quickly - right away before the frame finishes. But I dont think its use is recommended.