Understanding yield inside a for or a while loop

Hello guys,

I’m trying to understand how coroutines work. I’ve already read all of the documentation that unity has.

Here is what I’m trying to do:

        public void Awake()
        {
            StartCoroutine(cotest());
        }

        public IEnumerator cotest()
        {
            for (int x = 0; x <= 1000; x ++)
            {
                for (int y = 0; y <= 1000; y ++)
                {
                    //do something
                }
                Debug.Log("I'm in!!!");
                yield return new WaitForSeconds(0.1f);
            }
            
        }

I want the text “I’m in!!!” to be shown on the console 1000 times. But it only shows once.
It’s has if the the code never comes back to continue the yield.

Can you guys help me? What am I doing wrong?

I have to test your script, but it have to loop 1,2,3,4,5,etc.

I have to change the Debug.Log to test this

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour
{

    public void Awake()
    {
        StartCoroutine(cotest());
    }

    public IEnumerator cotest()
    {
        for (int x = 0; x <= 1000; x ++)
        {
            for (int y = 0; y <= 1000; y ++)
            {
                //do something
            }
            Debug.Log("I'm in!!! " + x); //<-- add a x to test this
            yield return new WaitForSeconds(0.1f);
        }

    }
}

It works the way you expect it to work. Your problem is that you have “Collapse” turned on in the Console. It’s a button on the left top of the console window. :wink: