void Awake()
{
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
}
void Start()
{
foreach (Transform child in transform)
{
Debug.Log(child.name);
}
}
In this code, I would not expect Debug.Log to be called, but it is.
Destroy generally doesn’t fully take effect until the end of the frame it’s called on. This is why DestroyImmediately is a separate function (and the docs on DestroyImmediately give a brief explanation as to why this is).
2 Likes
this is also why the foreach loop in awake doesn’t throw an exception. Normally you cannot change the IEnumerable while iterating it with a foreach loop (you cannot add or remove elements to it).
Unity allows this for game objects by destroying them actually at the end of frame. However you can check if they are null in the same frame and the == operator (or != operator) acts as if the object were null for destroyed game objects.
try this:
void Start()
{
foreach (Transform child in transform)
{
Debug.Log(string.Format("{0} is null: {1}", child.name, child.gameObject == null);
}
}
If I am not wrong the output is something like:
“GameObject is null: true”
1 Like