Figure: Diagnostic workflow: Define owner lifetime → Propagate cancellation → Handle cleanup on exit
Figure: Diagnostic workflow: Define owner lifetime → Propagate cancellation → Handle cleanup on exit

Cause and mechanism

await resumes the rest of a method after an operation such as a delay or network request completes. If its GameObject is destroyed during that wait, the resumed code can access a missing object. Pass a CancellationToken, a signal to stop the work, to operations that actually observe and handle cancellation.

Check and correct the setup

  1. Propagate a destruction token through awaited operations; Unity 2022.2+ also exposes destroyCancellationToken.
    The receiver must observe and handle cancellation
    The receiver must observe and handle cancellation
  2. Disable-scoped work needs a separate lifetime and a fresh token source when reenabled.
    The receiver must observe and handle cancellation
    The receiver must observe and handle cancellation
  3. Handle expected cancellation, release owned resources in finally, and use Unity APIs on the appropriate main thread.
    The receiver must observe and handle cancellation
    The receiver must observe and handle cancellation

Limits and verification

Canceling an await and stopping its underlying operation are API-dependent. Check the installed UniTask version and ownership after completion.

A focused diagnostic setup

Start a delayed action and test disabling versus destroying its object during the wait. Define which lifecycle event should end the operation.

Test in this order

  1. Propagate the intended lifetime token through lower-level waits and avoid destroyed references after awaits.
    The receiver must observe and handle cancellation
    The receiver must observe and handle cancellation
  2. For disable-scoped work, manage a new cancellation source per enable period rather than reusing a canceled token.
    The receiver must observe and handle cancellation
    The receiver must observe and handle cancellation
  3. Distinguish expected cancellation from other exceptions and clean up owned resources on every exit path.
    The receiver must observe and handle cancellation
    The receiver must observe and handle cancellation

Interpret the result

Canceling the await may leave the underlying load running. Define ownership of an eventual asset/handle result rather than assuming cancellation releases everything.

Related explanations

References