C# yield waitforseconds

How to set the yield waitforseconds in Unity3D C#? I looked for tutorials and stuff, but I still couldn’t figure it out. Now I am making a game and I want to use it, so anybody that can help me out with a good explanation, please no websites, just a clean explanation by yourself.

Kind regards,

helloiam.

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(2);
 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 after the wait goes after the yield statement and everything you want to happen before, goes before the yield statement. Hope this helps!

Or…

Avoid the problem altogether and use Invoke

From my StackOverflow answer:

This:

using UnityEngine;
using System.Collections;
public class MainCamera: MonoBehaviour {
  void Start () {
    Debug.Log ("About to StartCoroutine");
    StartCoroutine(TestCoroutine());
    Debug.Log ("Back from StartCoroutine");
  }
  IEnumerator TestCoroutine(){
    Debug.Log ("about to yield return WaitForSeconds(1)");
    yield return new WaitForSeconds(1);
    Debug.Log ("Just waited 1 second");
    yield return new WaitForSeconds(1);
    Debug.Log ("Just waited another second");
    yield break;
    Debug.Log ("You'll never see this"); // produces a dead code warning
  }
}

Produces this output:

About to StartCoroutine
about to yield return WaitForSeconds(1)
Back from StartCoroutine
Just waited 1 second
Just waited another second