Loop in coroutine stops after going halfway

I have a very weird problem with a particular loop in a coroutine:

    public IEnumerator DestroyCubesGameOver() {
    var startingCubeHolder = GameObject.FindWithTag("StartingCubeHolder");
    DestroyOutOfCameraCubes();

    Debug.Log(cubeGroup.transform.childCount);

    for (int i = 0; i < cubeGroup.transform.childCount; i++) {
        Debug.Log(i);
        Destroy(cubeGroup.transform.GetChild(i).gameObject);
        yield return new WaitForSeconds(0.001f);
    }

    Destroy(startingCubeHolder);
}

The loop starts doing its thing and it needs to do it 100 times for example. However it stops after going about halfway and after destroying about half of the objects. Even if I increase the delay for each repeat it still does the same exact thing - needs to repeat itself and destroy 100 objects, ends after destroying just 50. What is causing this?

Edit: If I make it just a void method it destroys all of the objects.

Edit 2: This loop was initially a foreach but I rewrote it to try the other way - same thing.

Try using gameObject.SetActive(false) instead of Destroy(object). What this will do is hide all of the objects in your scene by setting their ‘enabled’ property to false. This is technically the same thing as destroying an object because none of the scripts will fire on a disabled object.

If you absolutely need to destroy the objects, then I suggest trying to set the WaitForSeconds much higher, to about 1 or 2 full seconds. It isn’t good practice to destroy a large amount of objects quickly. Even if it works, you’re stuck with a bunch of dropped frames and lag :frowning:

This was the problem: on each loop I destroy one object so the childCount goes down. At the half my i and childCount meet and the loop stops.

Fixed it by setting the objects as inactive at first so that they can disappear from the player’s view and then destroying them without a coroutine later.