Using yield WaitForSeconds

Mike Tarrant picture Mike Tarrant · Jul 27, 2014 · Viewed 11.3k times · Source

I might be asking something that's extremely obvious and I have overlooked something, but I'm trying to create a pause before it does something.

I have seen this being used in many places online -

yield WaitForSeconds(2);

However I get a syntax error of,

"Error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) (CS1528) (Assembly-CSharp)

Which confuses me as im not really sure what yield as a keyword really means or does, and im under the assumption that WaitForSeconds is a class of its on with the "2" being in the constructor (not in a declaration) any help would be appreciated. thanks!

Answer

apxcode picture apxcode · Jul 27, 2014

What you want is t use an IEnumerator.

IEnumerator Example() 
{
    print(Time.time);
    yield return new WaitForSeconds(5);
    print(Time.time);
}

Then you will ask: How do I call this?

void Start() 
{
    print("Starting " + Time.time);
    StartCoroutine(WaitAndPrint(2.0F));
    print("Before WaitAndPrint Finishes " + Time.time);
}

IEnumerator WaitAndPrint(float waitTime) 
{
    yield return new WaitForSeconds(waitTime);
    print("WaitAndPrint " + Time.time);
}

I just read the link Jon Skeet posted on the comments, I too recommend it, it has pretty valuable information.