问题
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!
回答1:
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.
回答2:
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);
}
}
来源:https://stackoverflow.com/questions/24985451/using-yield-waitforseconds