Foreach always works on IEnumerable objects. The Transform class implements the IEnumerable interface and that’s why you actually can iterate over the transform object. UT implemented the IEnumerator like this:
// C# (copied from UnityEngine.dll)
private sealed class Enumerator : IEnumerator
{
private Transform outer;
private int currentIndex = -1;
public object Current
{
get { return this.outer.GetChild(this.currentIndex); }
}
internal Enumerator(Transform outer)
{
this.outer = outer;
}
public bool MoveNext()
{
int childCount = this.outer.childCount;
return ++this.currentIndex < childCount;
}
public void Reset()
{
this.currentIndex = -1;
}
}
So the foreach loop uses this Enumerator object to iterate through the childs of a Transform object. As you can see they didn’t implement any check if the “collection” has changed in between. That’s why you essentially skip every second child because you remove the first so the second become the first, the third become the second, …
Since the Enumerator increments the index each iteration you actually access index 0, 2, 4, 6, 8, …
Destroying the childs usually has the same effect. Maybe they changed something in the newer version of Unity.
Usually Enumerators should throw an Exception when the collection is changed during iteration. The List<...> Enumerator does this. If you Add or Remove an object while iterating a List in a foreach loop it would throw an InvalidOperationException with the text “collection was modified”.
To prevent such an Exception or the behaviour you’ve seen, create a “copy of the collection”. The Linq namespace adds a “ToList” method ro all IEnumerable which will create a List which will contain the elements of the collection.
However Unity only implements the non-generic IEnumerable interface and not IEnumerable so it has to be casted first:
foreach(var child in transform.Cast<Transform>().ToList())
{
//...
}
This usually work in all cases. Don’t forget to add
When we have a case of a foreach loop removing items and changing the IEnumerable, thus messing with the data structure, an elegant solution would be to use a plain old for loop and start from the end of the IEnumerable and therefore acting on the element before removing it. Since we’re removing items from the end of the data structure, its internal order is not disrupted mid flight.
For example:
for (int i = Children.Length - 1; i >= 0; i--)
{
///
}