TExcelTAD
Home › Unity with C# › async/await & Awaitable

async/await & Awaitable

Coroutines can't return values, can't wrap a yield in try/catch, and are tied to one MonoBehaviour. Since Unity 2023.1, Unity ships Awaitable, a pooled, engine-aware awaitable type for C#'s async/await. In Unity 6 it is the modern way to write sequences that span frames.

The Awaitable API

Call Resumes
await Awaitable.NextFrameAsync() next frame (like yield return null)
await Awaitable.WaitForSecondsAsync(t) after t seconds of scaled time
await Awaitable.FixedUpdateAsync() at the next fixed update
await Awaitable.EndOfFrameAsync() after rendering
await Awaitable.BackgroundThreadAsync() on a thread-pool thread (heavy work, no Unity API)
await Awaitable.MainThreadAsync() back on the main thread
await Awaitable.FromAsyncOperation(op) when an AsyncOperation (such as scene loading) completes

Each method takes an optional CancellationToken. Every MonoBehaviour has destroyCancellationToken, which is cancelled when the object is destroyed. Pass it, or your async method keeps running after its object is gone.

csharp
using System;
using System.Threading;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Door : MonoBehaviour
{
    [SerializeField] Transform panel;
    [SerializeField] float openHeight = 3f, duration = 1.2f;

    // async Awaitable: Unity's equivalent of async Task, without Task's allocations
    public async Awaitable<bool> OpenAsync(CancellationToken token)
    {
        Vector3 start = panel.localPosition, end = start + Vector3.up * openHeight;
        float t = 0f;
        while (t < duration)
        {
            t += Time.deltaTime;
            panel.localPosition = Vector3.Lerp(start, end, t / duration);
            await Awaitable.NextFrameAsync(token);
        }
        return true;
    }

    async void OnTriggerEnter(Collider other)          // async void only at "fire and forget" entry points
    {
        if (!other.CompareTag("Player")) return;
        try
        {
            bool opened = await OpenAsync(destroyCancellationToken);
            await Awaitable.WaitForSecondsAsync(0.5f, destroyCancellationToken);
            if (opened) await SceneManager.LoadSceneAsync("Level2");   // AsyncOperation is awaitable in Unity 6
        }
        catch (OperationCanceledException)
        {
            // the door was destroyed mid-animation: nothing to do
        }
    }
}

Warning: An Awaitable instance is pooled and can be awaited only once. Don't store it in a field and await it twice, and don't pass it to Task.WhenAll. If you need that, convert your logic to Task (with its allocations) or await things sequentially.

Two more rules: an exception thrown inside an async void method has no caller to catch it (Unity logs it to the Console), so keep try/catch inside such methods, and code after await Awaitable.BackgroundThreadAsync() must not touch the Unity API until you await Awaitable.MainThreadAsync().

A model: awaiting the game loop

C# lets any type be awaited if it has a GetAwaiter(). The model below builds a tiny NextFrame awaitable: awaiting it hands the rest of the method (the continuation) to a frame scheduler, which resumes it on the next tick. That is how Awaitable.NextFrameAsync works, minus the pooling. Cancellation works through a CancellationToken, like destroyCancellationToken.

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;

var loop = new FrameLoop();
var doorDestroyed = new CancellationTokenSource();

_ = FadeIn(loop);
_ = OpenDoor(loop, doorDestroyed.Token);

for (int frame = 1; frame <= 6; frame++)
{
    Console.WriteLine(
quot;frame {frame}"); if (frame == 4) { Console.WriteLine(" door destroyed"); doorDestroyed.Cancel(); } loop.Tick(); } static async Task FadeIn(FrameLoop loop) { for (int alpha = 0; alpha <= 100; alpha += 50) { Console.WriteLine(
quot; fade alpha {alpha}%"); await loop.NextFrame(); } Console.WriteLine(" fade finished"); } static async Task OpenDoor(FrameLoop loop, CancellationToken token) { try { for (int h = 0; h <= 4; h++) { Console.WriteLine(
quot; door height {h}"); await loop.NextFrame(token); } } catch (OperationCanceledException) { Console.WriteLine(" door animation cancelled"); } } class FrameLoop { List<Action> next = new(); public void Schedule(Action continuation) => next.Add(continuation); public void Tick() { var now = next; next = new(); // continuations scheduled now run next frame foreach (var c in now) c(); } public NextFrameAwaitable NextFrame(CancellationToken token = default) => new(this, token); } readonly struct NextFrameAwaitable : INotifyCompletion { readonly FrameLoop loop; readonly CancellationToken token; public NextFrameAwaitable(FrameLoop l, CancellationToken t) { loop = l; token = t; } public NextFrameAwaitable GetAwaiter() => this; public bool IsCompleted => false; // always suspend until the next frame public void OnCompleted(Action continuation) => loop.Schedule(continuation); public void GetResult() => token.ThrowIfCancellationRequested(); }
  fade alpha 0%
  door height 0
frame 1
  fade alpha 50%
  door height 1
frame 2
  fade alpha 100%
  door height 2
frame 3
  fade finished
  door height 3
frame 4
  door destroyed
  door animation cancelled
frame 5
frame 6

Like a coroutine, everything up to the first await runs immediately. The cancelled token makes GetResult throw OperationCanceledException at the await, so the door's catch runs and the method ends cleanly.

Coroutine or Awaitable?

Coroutine Awaitable
Return values no Awaitable<T>
try/catch around waits no yes
Stops with its object automatically only if you pass destroyCancellationToken
Background threads no BackgroundThreadAsync
Works in older Unity yes 2023.1+ / Unity 6

Both are fine. Teams usually pick one style for new code. Avoid Task.Delay and Task.Run in gameplay code: Task.Delay ignores Time.timeScale and doesn't stop when you exit Play mode.

Test yourself

How do you stop an async method when its MonoBehaviour is destroyed?

  1. It stops automatically, like coroutines
  2. Pass destroyCancellationToken to the Awaitable calls
  3. Call StopCoroutine
  4. Set Time.timeScale to 0

Which is true about an Awaitable instance?

  1. It can be awaited many times
  2. It is pooled and must be awaited only once
  3. It always runs on a background thread
  4. It allocates more than Task

After await Awaitable.BackgroundThreadAsync(), what must you do before setting transform.position?

  1. Nothing
  2. await Awaitable.MainThreadAsync()
  3. Call Task.Run
  4. Use a coroutine