Mike Tarrant
Mike Tarrant

Reputation: 291

Using yield WaitForSeconds

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!

Upvotes: 4

Views: 12779

Answers (2)

Roalt
Roalt

Reputation: 8440

You are using the Javascript code for Unity, and try it in the C# language, that´s why you get the error message.

If you click on the C# language selector on a page like http://docs.unity3d.com/ScriptReference/WaitForSeconds.html you will get the following example code for C#:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    IEnumerator Example() {
        print(Time.time);
        yield return new WaitForSeconds(5);
        print(Time.time);
    }
}

Upvotes: 0

axwcode
axwcode

Reputation: 7824

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.

Upvotes: 5

Related Questions