yield WaitForSeconds c#

How does yield WaitForSeconds work in c#?

i’ve tried, but I can’t seem to make it work, and I can’t find anything that helps me online!

I’m making a game, where when I look at a certain object, and the distance between me and the object is less than 2 I wan’t to do something. But only after, like 5 seconds. So I need the WaitForSeconds function. Please help me!!!

Invoke(“functionName”, 5.0f);

will invoke a function called functionName after 5 seconds…

As gjf stated, you could use invoke.

yield waitforseconds, however, is something you use inside a coroutine.

A coroutine is a block of code that executes on its own time frame. IE. not in Update/FixedUpdate/Etc.

IEnumerator ExecuteAfterTime(float time) {
    
    // stuff
    yield return new WaitForSeconds(time); // the program waits time seconds before continuing
   // more stuff
}

A coroutine is often used to make code that “blocks” while waiting for a condition to be true. Another good example is a spawning system where you want an item to spawn continuously, every X seconds:

IEnumerator SpawnPrefabContinuously() {
    while(true) {
        yield return new WaitForSeconds(spawnTime);
        SpawnPrefab();
    }
}

Another common yield statement is: yield return null doing this causes the coroutine to pause a single frame. You can then make alternate update blocks using this method. Some people never use update and just use a coroutine (though this isn’t always proper either).

It lets you separate time dependent code into separate code chunks instead of having a lot of branching logic inside update.

In c# you have to use an IEnumerator. Google for it :wink: or Unity - Scripting API: MonoBehaviour.StartCoroutine

void Event ()
{
    StartCoroutine("DoSomething");
}


IEnumerator DoSomething()
{
   yield return new WaitForSeconds(5f);
   print("Ok");
}

Call this outside of Start() or Update()…

IEnumerator wait()
{
   //Do whatever you need done here before waiting

   yield return new WaitForSeconds (2f);

   //do stuff after the 2 seconds
}

Call this in Update()…

StartCoroutine("wait");