Pardon our dust! Docs for Yarn Spinner for Unity 3.2 and Yarn Spinner for Godot C# are on docs.yarnspinner.dev (the old docs site). Docs for Yarn Spinner for Unity 3.3 (pre-release, out ASAP), Yarn Spinner for Godot GDScript and Yarn Spinner for Unreal Engine (work in progress) are on /docs/ (the new docs site).

Custom Actions

The custom Commands and Functions in this sample do more than return straight away. A Function waits while the player picks an item from their inventory, and a Command walks a character across the arena, which the player can skip. The Commands and Functions take a FoodType, an enum declared in the Yarn Script.

When you run it, Hungry Henry asks for an apple, an orange or a blueberry. Walk to the three piles of fruit at the back of the arena to collect some, then talk to Henry again. He shows your inventory and waits for you to choose. If you give him the right fruit, he walks off to eat it and comes back. Capsley, standing beside him, explains what’s going on.

The Custom Actions sample in Play mode: the inventory panel at the top of the screen shows five apples, three oranges and four blueberries, with the player, Hungry Henry and Capsley standing in the arena in front of the three piles of fruit.
The Custom Actions sample.

Running it

Open the CustomActions scene in the Custom Actions sample’s folder and press Play.

  • Move with W, A, S and D, or the arrow keys.
  • Walk up to a character or a pile of fruit and press Space to interact.
  • Press Space to continue. Press it while Henry is walking to skip the walk.
  • When the inventory picker is showing, click a fruit to give it to Henry.
  • Press Escape to stop the conversation. If you’re picking an item, this cancels the pick, and you keep the fruit.

How it works

The CustomFunctions script in CustomActions.cs keeps the inventory. Its Commands and Functions are static methods with the [YarnCommand] and [YarnFunction] attributes, which Yarn Spinner finds when your scripts compile:

In YarnKindWhat it does
<<add_inventory_item FoodType.Apple>>CommandAdds a fruit to the inventory. The fruit piles use it.
<<remove_inventory_item FoodType.Apple>>CommandRemoves a fruit from the inventory.
<<walk_to_point_eat_and_return "Hungry Henry" Marker>>CommandWalks Henry to the Marker GameObject, plays a bite sound, and walks him back. The player can skip it.
has_inventory_item(FoodType.Apple)FunctionWhether the inventory has any of that fruit.
has_any_inventory_items()FunctionWhether the inventory has anything in it.
inventory_count(FoodType.Apple)FunctionHow many of that fruit the inventory has.
pick_inventory_item()FunctionShows the inventory, waits for the player to choose a fruit, and returns it.
The Commands and Functions the sample adds.

Each fruit pile is an Item Vendor that runs one of the ItemVendor nodes in CustomActions-ItemVendors.yarn. Henry runs HungryHenry, and Capsley runs ExplanationCharacter, both in CustomActions.yarn.

The inventory panels use the InventoryPanel and InventoryItem scripts, in the sample’s Scripts folder. CustomFunctions maps each FoodType to its sprite, in its Item Sprites list in the Inspector.

Commands and Functions that take an enum

CustomActions.yarn declares the fruit as an enum:

<<enum FoodType>>
    <<case None = "none">>
    <<case Apple = "apple">>
    <<case Orange = "orange">>
    <<case Blueberry = "blueberry">>
<<endenum>>
The FoodType enum, in the HungryHenry node.

The Yarn Project has Generate Variables Source File turned on, with the class name CustomFunctionsVariables. The generated file includes a matching C# FoodType enum, and the Commands and Functions use it as their parameter type:

[YarnCommand("add_inventory_item")]
public static void AddInventoryItem(FoodType name, int count = 1)
{

    if (Instance.inventory.TryGetValue(name, out var currentCount) == false)
    {
        currentCount = 0;
    }

    Instance.inventory[name] = Mathf.Max(currentCount + count, 0);
    Instance.UpdateInventoryPanels();
}

[YarnFunction("inventory_count")]
public static int GetInventoryCount(FoodType itemName)
{
    return Instance.inventory.TryGetValue(itemName, out var count)
        ? count
        : 0;
}
Commands and Functions that take a FoodType.

<<add_inventory_item FoodType.Apple>> passes in FoodType.Apple. See Yarn enums.

A Function that waits for the player

pick_inventory_item() shows the inventory picker, and doesn’t return until the player has chosen. The dialogue pauses at the <<set>> until then:

[YarnFunction("pick_inventory_item")]
public static async YarnTask<string> PickInventoryItem(CancellationToken cancellationToken)
{
    const FoodType DefaultValue = FoodType.None;

    // If we don't have a panel to select from, or we don't have any items we could select, or we're already cancelled, return our default value
    if (Instance.selectionPanel == null
        || cancellationToken.IsCancellationRequested
        || !Instance.inventory.Any(kv => kv.Value > 0))
    {
        return DefaultValue.GetBackingValue();
    }

    // Create a completion source, which we use to signal that we have a result (and also to get a task we can await)
    var completionSource = new YarnTaskCompletionSource<FoodType>();

    // Also, register that we want to know when we've been cancelled. When we do, signal that we've selected the default value.
    var registration = cancellationToken.Register(() => completionSource.TrySetResult(DefaultValue));

    // A small local function that signals that we're done. (We'll store it in a local method)
    System.Action<FoodType> ItemPicked = (FoodType item) => completionSource.TrySetResult(item);

    // When the selection panel makes a selection, run this ItemPicked handler.
    Instance.selectionPanel.OnItemPicked += ItemPicked;
    try
    {
        // Show the right inventory panel
        Instance.isSelecting = true;
        Instance.UpdateInventoryPanels();

        // Wait until 
        var result = await completionSource.Task;
        return result.GetBackingValue();
    }
    finally
    {
        // This runs after we either successfully select an item, or some exception gets thrown.

        // Clean up by ending selection mode, removing the on clicked handler, and disposing of our 'on cancelled' handler.
        Instance.isSelecting = false;
        Instance.UpdateInventoryPanels();

        Instance.selectionPanel.OnItemPicked -= ItemPicked;
        registration.Dispose();
    }
}
Line 2 An async Function returns YarnTask<string>, the type of the value it ends up returning. Its last parameter is a CancellationToken, which the Dialogue Runner passes in. It isn’t written in the Yarn Script.
Lines 6–12 If there’s nothing to pick, or the dialogue has already been stopped, return "none" straight away.
Lines 14–24 A YarnTaskCompletionSource finishes with the fruit the player clicks, or with None if the dialogue is stopped while they’re choosing.
Lines 25–33 Show the picker, and wait here until the completion source finishes. The dialogue waits with it. A Function can’t return an enum, so it returns the fruit’s backing value, like "orange".
Lines 35–45 Whatever happens, hide the picker and stop listening.
PickInventoryItem in CustomActions.cs.

Henry’s node passes that value straight to <<remove_inventory_item>>, because a Command with an enum parameter accepts the enum’s backing value as well as its name:

// Pick an item from the inventory. The dialogue will pause until this is complete.
<<set $selected_food = pick_inventory_item()>>

<<if $selected_food is string($desired_food)>>
    // The player picked the desired item!

    // Remove the item from the inventory. 
    <<remove_inventory_item {$selected_food}>>
Line 2 The dialogue stops here until the player has chosen a fruit.
Line 4 Compare them as text, because $desired_food is a FoodType and $selected_food is its value as text.
Line 8 $selected_food holds a backing value like "orange", which the Command turns into FoodType.Orange.
Part of the HungryHenry node in CustomActions.yarn.

A Command the player can skip

<<walk_to_point_eat_and_return>> takes a few seconds. Its last parameter is a CancellationToken, so pressing Space while it’s running skips to the end:

[YarnCommand("walk_to_point_eat_and_return")]
public static async YarnTask MoveToPointAndReturn(GameObject target, Transform destination, CancellationToken cancellationToken)
{
    if (target.TryGetComponent<SimpleCharacter>(out var simpleCharacter) == false)
    {
        Debug.LogWarning($"{target.name} doesn't have a {nameof(SimpleCharacter)}");
        return;
    }

    simpleCharacter.transform.GetPositionAndRotation(out var originalPosition, out var originalLookDirection);

    // Walk to the target, pause a moment, and walk back
    await simpleCharacter.MoveTo(destination.position, cancellationToken);

    AudioSource? audioSource = Instance.audioSource;
    if (audioSource != null && audioSource.resource != null)
    {
        audioSource.Play();
    }

    await YarnTask.Delay(System.TimeSpan.FromSeconds(1), cancellationToken).SuppressCancellationThrow();
    await simpleCharacter.MoveTo(originalPosition, cancellationToken);

    // Restore our original look direction
    simpleCharacter.SetLookDirection(originalLookDirection);

    // Stop the audio in case it's still going and we got cancelled
    if (audioSource != null && audioSource.isPlaying)
    {
        audioSource.Stop();
    }
}
Line 2 "Hungry Henry" and Marker are GameObject names. The Dialogue Runner finds those GameObjects and passes them in, and adds the token itself.
Line 13 Walk to the marker. MoveTo() takes the token too. If the player skips, Henry jumps to the end of the walk.
Line 21 Wait a second, or less if the player skips. SuppressCancellationThrow() stops the skip from throwing an exception.
Lines 22–25 Walk back, and turn back to face the way he was.
MoveToPointAndReturn in CustomActions.cs.

The sample’s Line Advancer uses Key Codes. Space is Hurry Up Line, which moves on while a Command is running and cancels its token. Escape is Cancel Dialogue, which stops the dialogue. See Line Advancer.

For more about tokens, see Async and Cancellation.

Things to try

  • Add a fourth fruit. Add a case to the FoodType enum, a new pile with its own ItemVendor node, and a sprite for it in Item Sprites. The generated file picks up the new case when the Yarn Project reimports.
  • Give pick_inventory_item() a time limit. Create a CancellationTokenSource that cancels after a few seconds, link it to the token the Function is given, and Henry gets None if the player takes too long.

This sample uses models by Kay Lousberg, licensed under CC0, and the sound “Crispy bite” by JoMungus.

Next step Inline Events Trigger movement and emotions from inside a line of dialogue.