Last active
August 14, 2026 16:32
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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