0
0
Unityframework~5 mins

Async/await in Unity

Choose your learning style9 modes available
Introduction

Async/await helps your game run tasks like loading or waiting without freezing the screen. It keeps the game smooth and responsive.

Loading game data or assets without stopping the game
Waiting for a web request to finish while the player can still move
Delaying an action without freezing the whole game
Running background tasks like saving progress quietly
Syntax
Unity
async Task YourAsyncMethod()
{
    await SomeAsyncOperation();
    // code here runs after the operation finishes
}

Use async before the method to mark it as asynchronous.

Use await to pause the method until the awaited task finishes, without freezing the game.

Examples
This waits 2 seconds asynchronously, then prints a message.
Unity
async Task LoadDataAsync()
{
    await Task.Delay(2000); // wait 2 seconds
    Debug.Log("Data loaded");
}
This waits 1 second, then returns a score number.
Unity
async Task<int> GetScoreAsync()
{
    await Task.Delay(1000);
    return 42;
}
Calling an async method from Unity's Start method to load data without freezing.
Unity
async void Start()
{
    await LoadDataAsync();
    Debug.Log("Start finished");
}
Sample Program

This Unity script shows how async/await lets the game print messages before, during, and after a simulated 3-second loading without freezing the game.

Unity
using System.Threading.Tasks;
using UnityEngine;

public class AsyncExample : MonoBehaviour
{
    async void Start()
    {
        Debug.Log("Loading started...");
        await LoadDataAsync();
        Debug.Log("Loading finished!");
    }

    async Task LoadDataAsync()
    {
        await Task.Delay(3000); // simulate 3 seconds loading
        Debug.Log("Data loaded");
    }
}
OutputSuccess
Important Notes

Unity's main thread stays free while awaiting, so the game stays smooth.

Use async void only for Unity event methods like Start or Update. For others, use async Task.

Remember to include using System.Threading.Tasks; to use async/await.

Summary

Async/await lets your game do long tasks without freezing.

Mark methods with async and use await to pause without blocking.

Use async/await in Unity to keep gameplay smooth during loading or waiting.