Async and Cancellation

Some Commands, Functions and Presenters take time, like a Command that walks a character across the room or a Presenter that types a line out. Write them so they still behave correctly when the player hurries the dialogue along, the game is paused or the dialogue is stopped.

YarnTask

Yarn Spinner’s async methods return a YarnTask, or a YarnTask<T> when they return a value. You await a YarnTask the same way as any other task, and you can return one from your own async methods.

A YarnTask wraps one of three kinds of task, depending on your project. Yarn Spinner picks the first of these that’s available:

BackendUsed when
UniTaskThe UniTask package is installed.
AwaitableYou’re using Unity 2023.1 or later.
System.Threading.Tasks.TaskNeither of the others is available.
The three backends a YarnTask can use, in the order Yarn Spinner tries them.

Most of the time you don’t need to know which one you’re using. A YarnTask converts to and from the backend’s own type, and from the other kinds of task where they’re available. You can return a Task or an Awaitable where a YarnTask is expected.

YarnTask has static methods for common waits:

MethodWhat it does
YarnTask.Yield()Waits until the next frame.
YarnTask.Delay(milliseconds, token)Waits for a number of milliseconds, or a TimeSpan.
YarnTask.WaitUntil(predicate, token)Waits until predicate returns true.
YarnTask.WaitUntilCanceled(token)Waits until token is cancelled.
YarnTask.WhenAll(tasks)Waits until every task in tasks has finished.
YarnTask.CompletedTaskA task that has already finished. Return it from a method that has nothing to wait for.
Some of YarnTask’s static methods.

With UniTask and Awaitable, awaiting something that’s been cancelled throws an OperationCanceledException. To wait without the exception, add .SuppressCancellationThrow(). It returns true if the task was cancelled.

var cancelled = await YarnTask.Delay(2000, token).SuppressCancellationThrow();
Waiting for two seconds, or until the token is cancelled, without throwing.

How the dialogue waits

The dialogue waits for three kinds of things:

  • Commands: if a Command returns a YarnTask, a Task, an Awaitable, a UniTask, a Coroutine or an IEnumerator, the dialogue waits until it’s finished. See Commands.
  • Functions: if a Function is async and returns a task with a value, like YarnTask<int>, the dialogue waits for the value. See Functions that wait.
  • Presenters: the dialogue waits until every Presenter has finished RunLineAsync() or RunOptionsAsync(). See Building Your Own Presenter.

The player can ask a line to hurry up or move on. A Command can listen for the same requests, if it asks for a token.

Hurry up and next content

Every line and every set of options gets a new LineCancellationToken, which is passed to each Presenter’s RunLineAsync() or RunOptionsAsync(). The token tells the Presenters when the line has been asked to finish early. There are two kinds of request:

RequestWhat it meansWhat a Presenter should do
Hurry upFinish showing the line now.Skip to the end of any typing or animation, but keep the line on screen.
Next contentMove on.Tidy up and return as soon as possible.
The two requests a token can carry.

When the player presses the continue button, the Line Advancer asks for hurry up if the line is still appearing, and next content if it’s finished. The first press shows the whole line, and the second moves on:

sequenceDiagram
  participant Player
  participant Runner as Dialogue Runner
  participant Presenter as Your Presenter
  Runner->>Presenter: RunLineAsync(line, token)
  Note over Presenter: Typing the line
  Player->>Runner: Continue
  Runner->>Presenter: token: hurry up
  Note over Presenter: Shows the whole line
  Player->>Runner: Continue
  Runner->>Presenter: token: next content
  Presenter-->>Runner: returns from RunLineAsync()
  Note over Runner: The dialogue moves on
Two presses of the continue button while a line is typing.

You can ask for them from your own code too, with dialogueRunner.RequestHurryUpContent() and dialogueRunner.RequestNextContent(). Hurry up works for options too. When a Presenter picks an option, next content is requested for the options, which tells the other Presenters to stop waiting. Stop() asks for next content as well.

A request for next content also counts as hurry up. Check IsNextContentRequested when you need to tell them apart.

The token has these properties:

Part of the tokenWhat it does
IsHurryUpRequestedtrue once hurry up or next content has been requested.
IsNextContentRequestedtrue once next content has been requested.
HurryUpTokenA CancellationToken that’s cancelled when hurry up or next content is requested. Pass it to anything that should finish early.
NextContentTokenA CancellationToken that’s cancelled when next content is requested.
What you can use on a LineCancellationToken.

An example

This Presenter fades in a character’s portrait for each line. If the player hurries up, the portrait appears in full at once. It stays up until the dialogue moves on:

using UnityEngine;
using Yarn.Unity;

public class PortraitPresenter : DialoguePresenterBase
{
    [SerializeField] CanvasGroup portrait;

    public override async YarnTask RunLineAsync(LocalizedLine line, LineCancellationToken token)
    {
        portrait.alpha = 0;

        while (portrait.alpha < 1 && !token.IsHurryUpRequested)
        {
            portrait.alpha += Time.deltaTime;
            await YarnTask.Yield();
        }
        portrait.alpha = 1;

        await YarnTask.WaitUntilCanceled(token.NextContentToken).SuppressCancellationThrow();
        portrait.alpha = 0;
    }
}
Line 8 Every other method does nothing by default, so this Presenter only writes RunLineAsync.
Line 10 Start the fade from invisible.
Lines 12–16 Fade in over one second, a frame at a time, until the fade is done or hurry up is requested.
Line 17 Show the portrait fully, whether the fade finished or was hurried.
Line 19 Wait for next content. If it was requested already, this doesn’t wait.
Line 20 Hide the portrait, and return. The dialogue can move on.
A Presenter that fades in a portrait, and handles both requests.

Return promptly

Once next content has been requested, the Dialogue Runner can’t move on until every Presenter has returned. A Presenter that never returns holds up the dialogue for good. This usually means it’s waiting for something that will never happen, like a button press on a button that’s already been hidden.

When a request comes in, return from RunLineAsync() or RunOptionsAsync(). Don’t let an OperationCanceledException escape. If one does, the Dialogue Runner catches it and logs a warning that names the Presenter. Use SuppressCancellationThrow(), or catch the exception yourself, and then return.

Waiting in Commands

An async Command gets a token if the last parameter of its method is a CancellationToken or a LineCancellationToken. You don’t write it in the Yarn Script. The Dialogue Runner passes one in. Pressing continue, RequestHurryUpContent() and RequestNextContent() all reach it while the Command is running.

  • A CancellationToken is cancelled when the player asks to hurry up or to move on. It can’t tell the two apart.
  • A LineCancellationToken works the same way as a line’s, and can tell hurrying up from moving on.

This Command moves a cube, and jumps it straight to the end if the player asks to move on:

[YarnCommand("move_cube")]
public static async YarnTask MoveCube(float duration, CancellationToken token)
{
    var cube = GameObject.Find("Cube");
    var end = new Vector3(-5, 5, 0);
    var elapsed = 0f;
    while (elapsed < duration && !token.IsCancellationRequested)
    {
        cube.transform.position = Vector3.Lerp(Vector3.zero, end, elapsed / duration);
        elapsed += Time.deltaTime;
        await YarnTask.Yield();
    }
    cube.transform.position = end;
}
Line 2 <<move_cube 3>> calls it with duration set to 3. The token is the last parameter, and the Dialogue Runner adds it.
Lines 7–12 Move a little each frame, until the cube arrives or the player asks to move on.
Line 13 The cube always ends up at the end, where the writer expected it.
A move_cube Command that the player can skip.

What hurrying up and moving on mean for a Command is up to you. The token only tells you the player asked.

A Command without a token parameter doesn’t get one, and neither does a coroutine. While it’s running, pressing continue, RequestHurryUpContent() and RequestNextContent() do nothing, and the dialogue waits until the Command has finished. Keep its waits short, or show the player that something is happening.

To wait for a number of seconds in a Command, return a coroutine that uses WaitForSeconds, or a YarnTask from YarnTask.Delay():

void Awake()
{
    dialogueRunner.AddCommandHandler("pause_for_effect", PauseForEffect);
}

static IEnumerator PauseForEffect()
{
    yield return new WaitForSeconds(2);
}
A pause_for_effect Command that waits two seconds.

The player can skip the built-in <<wait>> Command, because it uses YarnTask.Delay() with the hurry-up token.

Functions that wait

A Function that’s async, and returns a task with a value like YarnTask<int>, pauses the dialogue until it returns. See Functions that wait.

If the last parameter of a Function is a CancellationToken, the Dialogue Runner passes one in. It’s cancelled when the dialogue no longer needs the Function’s value, such as when the dialogue is stopped. A Function that’s waiting can then stop waiting. Use a CancellationToken. A LineCancellationToken on a Function gives you warning YS1026, because hurrying up doesn’t apply to a Function: it’s waiting for a value, and there’s nothing to hurry. It’s waiting for a value, and there’s nothing to hurry.

Pausing the game

When you pause the game by setting Time.timeScale to 0, anything that counts scaled time stops:

  • The Line Presenter stops typing, and its fades stop.
  • Anything that uses WaitForSeconds stops counting.
  • <<wait>> uses YarnTask.Delay(), covered next.
  • YarnTask.Delay() stops counting with UniTask and Awaitable. With System.Threading.Tasks.Task, it counts real time and carries on.

The Line Advancer still reads input while Time.timeScale is 0, so stop it from advancing the dialogue while your pause menu is open.

For your own Presenters and Commands to pause too, count time with Time.deltaTime, WaitForSeconds or YarnTask.Delay() with UniTask or Awaitable.

Stopping the dialogue

Stop() asks the current line or options for next content, and ends the dialogue. Each Presenter’s OnDialogueCompleteAsync(token) is called, and whatever is awaiting RunDialogue() carries on. To wait until it’s finished, await it:

await dialogueRunner.Stop();
Stopping the dialogue, and waiting until it has finished.

The Dialogue Runner also stops the dialogue when it’s destroyed.

If a Command is waiting when the dialogue stops, the dialogue ends without waiting for it. A Command with a token gets a request to move on first. The Command’s own code carries on to the end, but the dialogue doesn’t continue after it. If the rest of a Command shouldn’t happen once the dialogue has stopped, check dialogueRunner.IsDialogueRunning after each await:

async YarnTask WalkHome()
{
    await WalkTo(door.position);
    if (!dialogueRunner.IsDialogueRunning)
    {
        return;
    }
    await WalkTo(home.position);
}
A walk_home Command, added with AddCommandHandler(), that stops part way if the dialogue is stopped.

Waiting for something that might already be done

Sometimes you want to wait for something that might have finished before you get round to waiting for it, like an event that’s already been invoked. Use a YarnTaskCompletionSource for this. It records that it has finished, and the value it finished with. Awaiting its Task returns at once if it’s already finished.

This Presenter starts loading a portrait when the dialogue starts, and waits for it in RunLineAsync(). If the portrait has already loaded by then, there’s no wait:

using UnityEngine;
using UnityEngine.UI;
using Yarn.Unity;

public class PortraitLoadingPresenter : DialoguePresenterBase
{
    [SerializeField] Image portrait;

    YarnTaskCompletionSource<Sprite> portraitLoading;

    public override YarnTask OnDialogueStartedAsync(System.Threading.CancellationToken token)
    {
        portraitLoading = new YarnTaskCompletionSource<Sprite>();
        var request = Resources.LoadAsync<Sprite>("Portraits/Rosa");
        request.completed += _ => portraitLoading.TrySetResult((Sprite)request.asset);
        return YarnTask.CompletedTask;
    }

    public override async YarnTask RunLineAsync(LocalizedLine line, LineCancellationToken token)
    {
        if (portrait.sprite == null)
        {
            portrait.sprite = await portraitLoading.Task;
        }
        await YarnTask.WaitUntilCanceled(token.NextContentToken).SuppressCancellationThrow();
    }
}
Lines 13–15 Start loading when the dialogue starts, and finish the completion source with the sprite when it has loaded. The first line might not need the portrait for a while.
Line 16 Return straight away, so the dialogue doesn’t wait for the load to start.
Lines 21–24 Wait for the sprite, only if it hasn’t been shown yet.
A Presenter that loads a portrait in the background.

Await a completion source’s Task once, and keep the result if you need it again. With Awaitable, a task can’t be awaited more than once.

A YarnTaskCompletionSource has:

  • TrySetResult(value), which finishes it with a value. It returns false, and does nothing, if it has already finished.
  • TrySetCanceled() and TrySetException(exception), which finish it with a cancellation or an error instead.
  • Task, which you await to get the value.

YarnTaskCompletionSource without a type finishes without a value.

Next step Localisation and Assets Translating lines, and how voice clips and images are found for each line.