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.

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 Yarn | Kind | What it does |
|---|---|---|
<<add_inventory_item FoodType.Apple>> | Command | Adds a fruit to the inventory. The fruit piles use it. |
<<remove_inventory_item FoodType.Apple>> | Command | Removes a fruit from the inventory. |
<<walk_to_point_eat_and_return "Hungry Henry" Marker>> | Command | Walks Henry to the Marker GameObject, plays a bite sound, and walks him back. The player can skip it. |
has_inventory_item(FoodType.Apple) | Function | Whether the inventory has any of that fruit. |
has_any_inventory_items() | Function | Whether the inventory has anything in it. |
inventory_count(FoodType.Apple) | Function | How many of that fruit the inventory has. |
pick_inventory_item() | Function | Shows the inventory, waits for the player to choose a fruit, and returns it. |
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 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;
}<<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();
}
}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."none" straight away.YarnTaskCompletionSource finishes with the fruit the player clicks, or with None if the dialogue is stopped while they’re choosing."orange".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}>>$desired_food is a FoodType and $selected_food is its value as text.$selected_food holds a backing value like "orange", which the Command turns into FoodType.Orange.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();
}
}"Hungry Henry" and Marker are GameObject names. The Dialogue Runner finds those GameObjects and passes them in, and adds the token itself.MoveTo() takes the token too. If the player skips, Henry jumps to the end of the walk.SuppressCancellationThrow() stops the skip from throwing an exception.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
FoodTypeenum, a new pile with its ownItemVendornode, 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 aCancellationTokenSourcethat cancels after a few seconds, link it to the token the Function is given, and Henry getsNoneif the player takes too long.
This sample uses models by Kay Lousberg, licensed under CC0, and the sound “Crispy bite” by JoMungus.