why does foreach work only 1/2 of a time?

ok I’ve finally found what’s wrong.

and I don’t get the behavior.

IF I do it this way:

private void RemoveWallsF(){
	Debug.Log("Number Of Children: " + transform.childCount);
	foreach(Transform Child in transform){
		Debug.Log("Here");
	//	Destroy(Child.gameObject);
		StaticSpawner.DeactivateMeF(Child.gameObject);
	}
}

I get:

Number Of Children: 40
Here // 20 counts in colapse

Reason is because I change the child’s parent when I deactivate him.

if I do:

private void RemoveWallsF(){
	Debug.Log("Number Of Children: " + transform.childCount);
	foreach(Transform Child in transform){
		Debug.Log("Here");
		Destroy(Child.gameObject);
	//	StaticSpawner.DeactivateMeF(Child.gameObject);
	}
}

I get:

Number Of Children: 40
Here // 40 counts in colapse

but why does it go through all if it’s destroyed it’s kinda same as it would go to a different parent, …

and so I did this:

private void RemoveWallsF(){
	Debug.Log("Number Of Children: " + transform.childCount);
	Transform[] Children = transform.GetComponentsInChildren<Transform>();
	Debug.Log(Children.Length);
	for (int i=1; i<Children.Length; i++) {
		Debug.Log("Here");
		StaticSpawner.DeactivateMeF(Children*.gameObject);*
  •   }*
    
  • }*
    I get:
    Number Of Children: 40
    Here // 40 counts in colapse
    I don’t understand the foreach loop, …
    why only 1/2 of a time, …

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, …

Here’s a visualization:

              C0 C1 C2 C3 C4  (childcount == 5)
index(0)      |

              C1 C2 C3 C4     (childcount == 4)
index(1)         |

              C1 C3 C4        (childcount == 3)
index(2)            |

              finished

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

using System.Linq;

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--)
{
    ///
}