| name | tools-unity-unitask |
| description | UniTask async/await patterns for Unity including cancellation, lifecycle binding, and coroutine interop. |
UniTask Async/Await for Unity
Overview
UniTask provides efficient async/await support for Unity with zero allocation, proper cancellation, and Unity lifecycle integration.
When to Use
- Async operations in Unity (loading, networking, delays)
- Replacing coroutines with async/await
- Managing cancellation in MonoBehaviours
- Async initialization patterns
- Parallel async operations
Installation
"com.cysharp.unitask": "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask"
Basic Patterns
Simple Async Method
public async UniTask LoadGameAsync()
{
await UniTask.Delay(1000);
await LoadAssetsAsync();
await InitializeSystemsAsync();
}
Async with Return Value
public async UniTask<PlayerData> LoadPlayerAsync()
{
var json = await File.ReadAllTextAsync(path);
return JsonUtility.FromJson<PlayerData>(json);
}
Fire-and-Forget (Use Carefully!)
LoadGameAsync().Forget();
public async UniTaskVoid StartBackgroundTask()
{
try
{
await DoWorkAsync();
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
Cancellation Patterns
Basic CancellationToken
public class GameLoader : MonoBehaviour
{
private CancellationTokenSource _cts;
private void OnEnable()
{
_cts = new CancellationTokenSource();
LoadAsync(_cts.Token).Forget();
}
private void OnDisable()
{
_cts?.Cancel();
_cts?.Dispose();
_cts = null;
}
private async UniTask LoadAsync(CancellationToken ct)
{
await UniTask.Delay(1000, cancellationToken: ct);
}
}
Destroy CancellationToken (Preferred for MonoBehaviour)
public class Enemy : MonoBehaviour
{
private async UniTaskVoid Start()
{
var ct = this.GetCancellationTokenOnDestroy();
while (!ct.IsCancellationRequested)
{
await UniTask.Delay(1000, cancellationToken: ct);
Patrol();
}
}
}
Linked Cancellation
public async UniTask DoWorkAsync(CancellationToken externalCt)
{
var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
externalCt,
this.GetCancellationTokenOnDestroy()
);
try
{
await LongRunningTask(linkedCts.Token);
}
finally
{
linkedCts.Dispose();
}
}
Timeout
await task.Timeout(TimeSpan.FromSeconds(5));
var (hasValue, result) = await task.TimeoutWithoutException(TimeSpan.FromSeconds(5));
if (!hasValue)
{
Debug.Log("Operation timed out");
}
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await task.AttachExternalCancellation(cts.Token);
Unity Lifecycle Integration
Waiting for Frames
await UniTask.Yield();
await UniTask.WaitForEndOfFrame();
await UniTask.WaitForFixedUpdate();
await UniTask.DelayFrame(10);
await UniTask.Yield(PlayerLoopTiming.PreUpdate);
Player Loop Timing Options
PlayerLoopTiming.Initialization
PlayerLoopTiming.EarlyUpdate
PlayerLoopTiming.FixedUpdate
PlayerLoopTiming.PreUpdate
PlayerLoopTiming.Update
PlayerLoopTiming.PreLateUpdate
PlayerLoopTiming.PostLateUpdate
PlayerLoopTiming.TimeUpdate
Waiting for Conditions
await UniTask.WaitUntil(() => player.IsReady);
await UniTask.WaitWhile(() => isLoading);
await UniTask.WaitUntil(
() => player.IsReady,
cancellationToken: ct
);
await UniTask.WaitUntil(() => player.IsReady)
.Timeout(TimeSpan.FromSeconds(10));
Waiting for Unity Events
await button.OnClickAsync();
var other = await gameObject.OnTriggerEnterAsync();
var collision = await gameObject.OnCollisionEnterAsync();
await animator.WaitForAnimationEvent("AttackHit");
Parallel Operations
WhenAll (Wait for All)
var results = await UniTask.WhenAll(
LoadTexturesAsync(),
LoadAudioAsync(),
LoadConfigAsync()
);
var (textures, audio, config) = await UniTask.WhenAll(
LoadTexturesAsync(),
LoadAudioAsync(),
LoadConfigAsync()
);
WhenAny (Wait for First)
var (winIndex, result1, result2) = await UniTask.WhenAny(
TryServerAAsync(),
TryServerBAsync()
);
if (winIndex == 0)
{
UseResult(result1);
}
Throttling Parallel Operations
var semaphore = new SemaphoreSlim(3);
await UniTask.WhenAll(items.Select(async item =>
{
await semaphore.WaitAsync();
try
{
await ProcessItemAsync(item);
}
finally
{
semaphore.Release();
}
}));
Coroutine Interop
Convert Coroutine to UniTask
await MyCoroutine().ToUniTask();
await MyCoroutine().ToUniTask(cancellationToken: ct);
IEnumerator LegacyCoroutine()
{
yield return new WaitForSeconds(1);
}
await LegacyCoroutine().ToUniTask();
Convert UniTask to Coroutine
StartCoroutine(MyUniTask().ToCoroutine());
Async Trigger Components
var trigger = gameObject.GetAsyncTriggerEnterTrigger();
var other = await trigger.OnTriggerEnterAsync();
Resource Loading
Addressables Integration
public async UniTask<T> LoadAssetAsync<T>(string address, CancellationToken ct)
{
var handle = Addressables.LoadAssetAsync<T>(address);
try
{
return await handle.ToUniTask(cancellationToken: ct);
}
catch (OperationCanceledException)
{
Addressables.Release(handle);
throw;
}
}
Scene Loading
public async UniTask LoadSceneAsync(string sceneName, CancellationToken ct)
{
await SceneManager.LoadSceneAsync(sceneName)
.ToUniTask(cancellationToken: ct);
}
public async UniTask LoadSceneWithProgressAsync(string sceneName, IProgress<float> progress)
{
await SceneManager.LoadSceneAsync(sceneName)
.ToUniTask(progress: progress);
}
Asset Bundle Loading
public async UniTask<AssetBundle> LoadBundleAsync(string url, CancellationToken ct)
{
var request = UnityWebRequestAssetBundle.GetAssetBundle(url);
await request.SendWebRequest().ToUniTask(cancellationToken: ct);
if (request.result != UnityWebRequest.Result.Success)
{
throw new Exception(request.error);
}
return DownloadHandlerAssetBundle.GetContent(request);
}
Error Handling
Try-Catch Pattern
public async UniTask SafeLoadAsync()
{
try
{
await LoadDataAsync();
}
catch (OperationCanceledException)
{
Debug.Log("Load cancelled");
}
catch (Exception ex)
{
Debug.LogException(ex);
ShowErrorUI();
}
}
SuppressCancellationThrow
var (cancelled, result) = await LoadAsync()
.SuppressCancellationThrow();
if (cancelled)
{
return;
}
ProcessResult(result);
Exception Handling in WhenAll
try
{
await UniTask.WhenAll(tasks);
}
catch (AggregateException ae)
{
foreach (var ex in ae.InnerExceptions)
{
Debug.LogException(ex);
}
}
Progress Reporting
IProgress
public async UniTask LoadWithProgressAsync(IProgress<float> progress, CancellationToken ct)
{
var items = await GetItemsAsync();
for (int i = 0; i < items.Count; i++)
{
await ProcessItemAsync(items[i], ct);
progress?.Report((float)(i + 1) / items.Count);
}
}
var progress = new Progress<float>(p => loadingBar.value = p);
await LoadWithProgressAsync(progress, ct);
Custom Progress
public struct LoadProgress
{
public string CurrentItem;
public int Loaded;
public int Total;
public float Percent => (float)Loaded / Total;
}
public async UniTask LoadAsync(IProgress<LoadProgress> progress)
{
var items = await GetItemsAsync();
for (int i = 0; i < items.Count; i++)
{
progress?.Report(new LoadProgress
{
CurrentItem = items[i].Name,
Loaded = i + 1,
Total = items.Count
});
await ProcessItemAsync(items[i]);
}
}
UniTask vs Task
When to Use UniTask
await UniTask.Delay(1000);
await UniTask.Yield();
await SceneManager.LoadSceneAsync(s);
DoWorkAsync().Forget();
When to Use Task
await File.ReadAllTextAsync(path);
await Task.Run(() => HeavyComputation());
var result = await task.AsUniTask();
var task = unitask.AsTask();
Common Pitfalls
Pitfall 1: Missing CancellationToken
public async UniTaskVoid Start()
{
await UniTask.Delay(10000);
DoSomething();
}
public async UniTaskVoid Start()
{
await UniTask.Delay(10000, cancellationToken: destroyCancellationToken);
DoSomething();
}
Pitfall 2: Forget Without Error Handling
DoWorkAsync().Forget();
async UniTaskVoid DoWorkSafe()
{
try
{
await DoWorkAsync();
}
catch (Exception ex) when (!(ex is OperationCanceledException))
{
Debug.LogException(ex);
}
}
DoWorkSafe().Forget();
Pitfall 3: Blocking on Main Thread
var result = LoadAsync().GetAwaiter().GetResult();
var result = await LoadAsync();
Pitfall 4: Unnecessary Allocations
await UniTask.Delay(1000).ContinueWith(_ => DoSomething());
await UniTask.Delay(1000);
DoSomething();
Best Practices
- Always use CancellationToken for MonoBehaviour async methods
- Use GetCancellationTokenOnDestroy() for automatic cleanup
- Handle OperationCanceledException separately from other exceptions
- Prefer UniTask over Task for Unity operations
- Use WhenAll for parallel operations
- Report progress for long-running operations
- Use SuppressCancellationThrow for optional cancellation handling
- Avoid Forget() without proper error handling
Performance Tips
- UniTask is struct-based (zero allocation when awaited directly)
- Avoid unnecessary
.AsTask() conversions
- Use
UniTask.Yield() instead of await UniTask.Delay(0)
- Pool
CancellationTokenSource for high-frequency operations
- Use
UniTaskCompletionSource for custom async patterns