Skip to content

Instantly share code, notes, and snippets.

@rob5300
Last active August 14, 2026 16:32
Show Gist options
  • Select an option

  • Save rob5300/a54605c0505fef49b9a46ed619f73af6 to your computer and use it in GitHub Desktop.

Select an option

Save rob5300/a54605c0505fef49b9a46ed619f73af6 to your computer and use it in GitHub Desktop.
Simpler example on how to use a cancellation token to stop an async function on a Unity MonoBehaviour
using Cysharp.Threading.Tasks;
using System;
using System.Threading;
using UnityEngine;
public class UniTaskDemo_CancellationToken : MonoBehaviour
{
void Start()
{
//Start our example!
AnimateExample().Forget();
}
/// <summary>
/// Animate to a destination position
/// </summary>
public async UniTask Animate(Vector3 destination, float duration)
{
//Get unity provided token for this component
var token = destroyCancellationToken;
float lerp = 0f;
Vector3 startPos = transform.position;
while(lerp < 1f && !token.IsCancellationRequested)
{
lerp += Time.deltaTime / duration;
transform.position = Vector3.Lerp(startPos, destination, lerp);
//await next frame (note the token argument for this to be cancelled early!)
await UniTask.Yield(token).SuppressCancellationThrow();
}
if(!token.IsCancellationRequested)
{
transform.position = destination;
Debug.Log($"Successfully animated to '{destination}'", this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment