Why does a check for null in a foreach loop make Destroying work?

For example, this code:

foreach (Transform child in transform) Object.DestroyImmediate(child.gameObject);

results in the error

The object of type 'Transform' has been destroyed but you are still trying to access it.

However, this code:

foreach (Transform child in transform) 
     if (child) Object.DestroyImmediate(child.gameObject);

seems to work perfectly. Why is that?

This is just hunch, but the unity docs say to use Object.Destroy instead of Object.DestroyImmediate. Its possible that you are confusing the iterator.

I ran into this same issue, though in my case it resulted in only partial removal of children. Here's what I originally tried doing, in JavaScript:

for (var child : Transform in obj.transform) {
    DestroyImmediate(child.gameObject);
}

This code does not delete all the children with unpredictable behavior. After reading this post, I came up with the following solution:

var children : Transform[] = new Transform[obj.transform.childCount];
var x = 0;
for (var child : Transform in obj.transform) {
    children[x] = child;
    x++;
}

if(children) {
    for (var child : Transform in children) {
        if(child) {
            DestroyImmediate(child.gameObject);
        }
    }
}

First thank you for the solution of how to simply destroy childern in a for loop. I think The reason it fails without the null check is that by destroying an object you are changing the hash value and therefore ordering of the childern in the list. So you can encounter a child again after it is destroyed. Have you checked that all childern are destroyed with null checking in place.