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 or use the inbuilt functions like coroutine or await. If your intention is not to display the timer then there is no need to make a timer function in Unity. 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.

Here is the code

using UnityEngine;
using System.Threading.Tasks;

public class Play_audio : MonoBehaviour
{

    async void Start()
        {
  
         await Task.Delay(1000)
         Your_fncton();   
            
        }
}
  1. Add using System.Threading.Tasks namespace to your script.
  2. Set the function where you want to delay as async. In this case it’s the start function.
  3. Use code await Task.Delay(delay time in milli seconds).
  4. Call the code to be delayed after await statement.

Using async await to delay foreach loop

async void Start()
    {
                

        foreach(String n in Clip)
        {                      
            await Task.Delay(1000); //Task.Delay input is in milliseconds
            Debug.Log(n);   
            
        }
    }

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.

Why Creativity is must for game developers How to become a Unity developer? How to Become a Game Developer? VR Game dev Companies: Top 10 Programming Languages used by Unity
%d bloggers like this: