Unity3D之C# yield waitforseconds

时间:2025-01-19 23:35:08

Wait for seconds requires a couple things in order to work properly and chances are if it's not working you're probably just missing on of the requirements. Here's an example:

IEnumerator MyMethod() {
Debug.Log("Before Waiting 2 seconds");
yield return new WaitForSeconds();
Debug.Log("After Waiting 2 Seconds");
}

Simple right? The only trick here is to make sure the return type of the method using the `WaitForSeconds` call is `IEnumerator`. Okay, so now we're half done but the next thing is to call this `MyMethod` and that looks like:

StartCoroutine(MyMethod());

And there's the 2nd trick. You need to call the method as a coroutine otherwise you're not going to have it work.

Now that you get how it works, jump back to the yield statement. Anything you want to happen afterthe wait goes after the yield statement and everything you want to happen before, goes before the yield statement. Hope this helps!