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();
}
}
- Add using System.Threading.Tasks namespace to your script.
- Set the function where you want to delay as async. In this case it’s the start function.
- Use code await Task.Delay(delay time in milli seconds).
- 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);
}
}
That HANGS everything and does not recover.
Please share your code.