How to create a C# method for waiting a number of seconds in unity by WaitForSeconds()

You can use yield return new WaitForSeconds() in a coroutine if you want to wait for a specific amount of time in unity.

Coroutine pause execution of code when it reaches at yield return and wait for the time we passed in WaitForSeconds(Seconds) method and then execute code that is after this statement.   WaitForSeconds(Seconds) takes only single parameter that is number of seconds we want to wait.

create a C# method for waiting a number of seconds in unity

A coroutine example for waiting for 2 seconds is given below:

Code :
IEnumerator ExampleCoroutine()
{
    yield return new WaitForSeconds(2);
    Debug.Log("2 seconds have passed");
}
Now we can call this coroutine in StartCoroutine() method.
Code :
void Start()
{
    StartCoroutine(ExampleCoroutine());
}

StartCoroutine() can only be called from MonoBehaviour component which is attached with a gameObject.


We can also use WaitForSecondsRealtime() instead for WaitForSeconds() statement both work in same way there is only a single difference that WaitForSecondsRealtime() wait for time in real time regardless of game status whether game is paused or not like timeScale is 0, 1 or anything else.

A coroutine example for waiting for 2 seconds in real-time and then print message is given below:

Code :
IEnumerator ExampleCoroutine()
{
    yield return new WaitForSecondsRealtime(2);
    Debug.Log("2 seconds of real-time have passed");
}


We can set  Time.timeScale value to 0 so it will pause all physics and animations and after that time passed we can set Time.timeScale value back to 1.

Code :
IEnumerator ExampleCoroutine()
{
    Time.timeScale = 0;
    float startTime = Time.realtimeSinceStartup;
    while (Time.realtimeSinceStartup < startTime + 1)
    {
        yield return null;
    }
    Time.timeScale = 1;
    Debug.Log("1 seconds of real-time have passed");
}

Now we use DateTime.Now.AddSeconds(1) to add a second in current time and then we use while loop for checking if current time is greater then our added time.

Code :
IEnumerator ExampleCoroutine()
{
    DateTime endTime = DateTime.Now.AddSeconds(1);
    while (DateTime.Now < endTime)
    {
        yield return null;
    }
    Debug.Log("1 seconds of real-time have passed");
}

You must note that you can use any method according to your need.


Comments