Search code examples
c#unity-game-enginewait

Can somebody please explain WaitForSeconds()?


I am trying to make my code wait x seconds before doing something. I looked up how to do this, and found out about the WaitForSeconds() function. Unfortunately, whenever I try to use it I get red underlines in my code. I am trying to make it so when you die it waits a few seconds before you respawn:

 void Respawn()
{
    yield return new WaitForSeconds(5);
    gameObject.transform.position = spawnPoint;
}

I also understand I need to put something like StartCoroutine(Example()); somewhere but I also don't know where to put it. How do I do this properly?


Solution

  • yield return new WaitForSeconds(5); must be used in a coroutine function. Right now, you are using it in a void function void Respawn(). Changing the void to IEnumerator should fix your problem.

    IEnumerator Respawn()
    {
        yield return new WaitForSeconds(5);
        gameObject.transform.position = spawnPoint;
    }
    

    Then you can call it with StartCoroutine(Respawn());. Each time you call it, it will wait for 5 seconds, then execute gameObject.transform.position = spawnPoint;. Visit here if you want to learn how it works.