0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ I just had a similar issue with a coroutine behaving weirdly. Try adding continue; after your yield statement. \$\endgroup\$ – Leggy7 May 15 '16 at 18:40
  • \$\begingroup\$ @Leggy7 Didn't help. Still stops after going halfway. This is so odd. \$\endgroup\$ – Milen May 15 '16 at 18:43
1
\$\begingroup\$

On each loop you destroy one object so your childcount goes down, at the half your i and childcount meet and the loop stops.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.