unity3d Coroutines Ways to yield


Example

You can wait until the next frame.

yield return null; // wait until sometime in the next frame

You can have multiple of these calls in a row, to simply wait for as many frames as desired.

//wait for a few frames
yield return null;
yield return null;

Wait for approximately n seconds. It is extremely important to understand this is only a very approximate time.

yield return new WaitForSeconds(n);

It is absolutely not possible to use the "WaitForSeconds" call for any form of accurate timing.

Often you want to chain actions. So, do something, and when that is finished do something else, and when that is finished do something else. To achieve that, wait for another coroutine:

yield return StartCoroutine(coroutine);

Understand that you can only call that from within a coroutine. So:

StartCoroutine(Test());

That's how you start a coroutine from a "normal" piece of code.

Then, inside that running coroutine:

Debug.Log("A");
StartCoroutine(LongProcess());
Debug.Log("B");

That will print A, start the long process, and immediately print B. It will not wait for the long process to finish. On the other hand:

Debug.Log("A");
yield return StartCoroutine(LongProcess());
Debug.Log("B");

That will print A, start the long process, wait until it is finished, and then print B.

It's always worth remembering that coroutines have absolutely no connection, in any way, to threading. With this code:

Debug.Log("A");
StartCoroutine(LongProcess());
Debug.Log("B");

it is easy to think of it as being "like" starting the LongProcess on another thread in the background. But that is absolutely incorrect. It is just a coroutine. Game engines are frame based, and "coroutines" in Unity simply allow you to access the frames.

It is very easy to wait for a web request to complete.

void Start() {
    string url = "http://google.com";
    WWW www = new WWW(url);
    StartCoroutine(WaitForRequest(www));
}

IEnumerator WaitForRequest(WWW www) {
    yield return www;
    
    if (www.error == null) {
        //use www.data);
    }
    else {
        //use www.error);
    }
}

For completeness: In very rare cases you use fixed update in Unity; there is a WaitForFixedUpdate() call which normally would never be used. There is a specific call (WaitForEndOfFrame() in the current version of Unity) which is used in certain situations in relation to generating screen captures during development. (The exact mechanism changes slightly as Unity evolves, so google for the latest info if relevant.)