- Home /
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?
Answer by YikYikHeiHei · Aug 20, 2011 at 08:13 AM
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);
}
}
}
That's because you also have collapse turned on, which collapses duplicate messages in the console, but are now changing the message each time.
It worked. I guess the Debug.Log only show a new message if it's different from the last one.
Thank you very much :)
Answer by Joshua · Aug 20, 2011 at 08:15 AM
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. ;)
Thanks for the extra info, I would thumb you up but the site is giving me an error :(