C# Yield

I’m having problems getting Yield to work in C#
I essentially looked through the scripting manual and
based my code on the example, but the code below doesn’t seem to yield for five seconds as intended.
Can anyone help? Thanks.


public class Test : MonoBehaviour {

int state;

IEnumerator YieldForTime (float secs) {
yield return new WaitForSeconds(secs);
}

void Start () {
state = 1;
}

void Update () {
switch (state) {
case 1:
// Delay for 5 seconds
StartCoroutine(YieldForTime(5.0f));

// After 5 seconds we switch to next state
state = 2;
break;

case 2:
//…
break;
}
}

Update runs every frame, and you can’t yield in it.

–Eric

This is what you want:

// C# example
// In this example we show how to invoke a coroutine and wait until it
// is completed

IEnumerator Start () {
// - After 0 seconds, prints "Starting 0.0"
// - After 2 seconds, prints "WaitAndPrint 2.0"
// - After 2 seconds, prints "Done 2.0"
print ("Starting " + Time.time);
// Start function WaitAndPrint as a coroutine. Wait until it is completed
yield return StartCoroutine(WaitAndPrint(2.0F));
print ("Done " + Time.time);
}

IEnumerator WaitAndPrint (float waitTime) {
// pause execution for waitTime seconds
yield return new WaitForSeconds (waitTime);
print ("WaitAndPrint "+ Time.time);
}

Do your state machine in Start() instead of Update(), since Update is called every frame like Eric said.

Alex

I see. I expected that because the script had been yielded then Update would not be called until after that yield duration. But obviously not the case. Thanks.