Address
304 North Cardinal St.
Dorchester Center, MA 02124

Work Hours
Monday to Friday: 7AM - 7PM
Weekend: 10AM - 5PM

Unity WaitForSeconds

Unity WaitForSeconds – Wait before executing a function

On Unity, the easiest way to wait before executing a function is to use WaitForSeconds.
You can use WaitForSeconds only in the context of a coroutine.

Setting it up

The first step is to create a coroutine with the StartCoroutine function.
Then, we use the yield instruction coupled with a new instance of WaitForSeconds.

As its name suggests, WaitForSeconds will wait for execution for X number of seconds.
X is a float and the first parameter of the function.

Here’s a concrete example where you want to wait 5 seconds before the start of a game:

    using System.Collections;
    using UnityEngine;

    private void Start()
    {
        StartCoroutine(StartGameCoroutine());
    }

    private IEnumerator StartGameCoroutine()
    {
        yield return new WaitForSeconds(5f);
        StartGame();
    }

However, WaitForSeconds cannot have a value less than the execution time of a frame.

For example, in a game running at 60 FPS, the execution of a frame is 0.0166666666666667 seconds. WaitForSeconds cannot have a value below this value.

Pro Tips

You’ll instantiate WaitForSeconds so many times in Unity that, you won’t be able to count them.

The only problem is that WaitForSconds is not cached, so each initialization consumes performance.
The gain may seem insignificant, but it remains a point for improvement.

You can cache them by using a C# class like this:

using System.Collections.Generic;
using UnityEngine;

namespace App.GameTime
{
    public static class TimerCoroutine
    {
        private static Dictionary<float, WaitForSeconds> _cacheWaitForSeconds = new Dictionary<float, WaitForSeconds>();

        public static WaitForSeconds WaitForSeconds(float value)
        {
            if (_cacheWaitForSeconds.ContainsKey(value))
            {
                return _cacheWaitForSeconds[value];
            }

            _cacheWaitForSeconds[value] = new WaitForSeconds(value);
            return _cacheWaitForSeconds[value];
        }
	}
}

Admittedly, it won’t be a revolutionary improvement.
But any performance boost is good to take =)

Learn more

Leave a Reply

Your email address will not be published. Required fields are marked *