How to create a delay in Unity using Async await

There are multiple ways to delay a task in Unity. You can either make your own timer function or use the inbuilt feature like async await. If your intention is not to display the timer then there is no need to make a timer function in Unity. You will delay a lot of tasks, during your journey of making your own game and while learning Unity. So, this is an important C# feature to master.

In this tutorial, we will see how to use async await to delay a task in Unity. I am using Unity 2021, if you are using a Unity version less than 2018 then async will not work, you will have to use a coroutine to delay your task.

We will start with a simple code, that will debug log a message after a delay of 2 seconds. To use the async delay, follow the steps below.

  1. Add using System.Threading.Tasks namespace to your script.
  2. Set the function type, where you want to execute the delay as async. In the below code, it’s the start function.
  3. Use await Task.Delay(delay time in milli seconds).
  4. Call the code to be delayed after await statement.

Here is the complete code with all the above steps executed.

using UnityEngine;
using System.Threading.Tasks;

public class Example_timer : MonoBehaviour
{
    async void Start()
        {  
            await Task.Delay(2000); //time in millisecond
            Debug.Log("Called after 2 seconds of game start");             
        }

}

Using async await to delay foreach loop

The unique feature of async is, it can be used to delay each loop of a for or foreach loop. The below code delays every loop by 1 second. As we saw in the play audio clip tutorial, we can use this to play audio clips in a sequence.

using UnityEngine;
using System.Threading.Tasks;

public class Example_timer : MonoBehaviour
{
    async void Start()
    { 

        for(int i=0;i<10;i++)
        {                   
            await Task.Delay(1000); //time input is in milliseconds
            Debug.Log(i);   
            
        }
    }

}

Hope the concept of Async await is clear. If you have any other questions, feel free to leave a comment below.

For the next tutorial, let’s create an Enemy AI that follows the player using Navmesh.

2 thoughts on “How to create a delay in Unity using Async await”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading