Skip to content
Author: yuantianle

Awaitable⚓︎

What is an "Awaitable" in Unity?

An awaitable is not unique to Unity, but rather a general term in C# that refers to any object that can be awaited using the await keyword. For an object to be awaitable, it must implement the GetAwaiter() method, which returns an Awaiter. This Awaiter must implement methods like IsCompleted, OnCompleted(Action continuation), and GetResult().

  • In C#, tasks (Task or Task<T>) are the most common awaitable objects, meaning you can call await on them. When you await something, you're telling the program to asynchronously wait for its completion without blocking the main thread.

  • In Unity, when we refer to something as awaitable, we mean an object or operation (e.g. frames or physics updates) that can be awaited using async/await. Unity traditionally uses coroutines for asynchronous programming, but newer versions (2023.1+) introduced the Awaitable class for more efficient async operations.

Old way of asynchronous programming in Unity

Unity traditionally uses coroutines for asynchronous programming because it was the primary way to handle tasks that needed to occur over time without blocking the main thread prior to the introduction of async/await. Coroutines in Unity allow developers to write code that "waits" for certain conditions (like a delay, waiting for a frame, or a physics update) without halting the entire game loop. This made coroutines a very flexible tool for tasks like animations, timed events, or other frame-based operations.

Introducing of Awaitable in Unity

In Unity 2023.1+, the Awaitable class was introduced to provide a more efficient way to handle asynchronous operations. It allows developers to use async/await syntax in Unity and designed to optimize async/await patterns for Unity's game engine.

How to use Awaitable?

Conclusion:Features of Awaitable?
  • the asynchronous calculation can be stopped alt text
  • automatically deconstructed after completion alt text alt text
  • can switch between main thread and background threads alt text
  • Task delay cannot be used in WebGL, but awaitable can alt text
  • Awaitable objects are pooled and reused to avoid excessive memory allocations, which helps improve performance in environments like WebGL and mobile platforms​

Reference⚓︎

Comments