Commands

A Command is a line in a Yarn Script that tells your game to do something. It’s written inside << and >>, with the Command’s name first and any arguments after it:

title: CommandsExample
---
<<play_sound door_creak>>
Rosa: Oh! You gave me a fright.
<<move Rosa 3 0>>
<<wait 1>>
Rosa: Here, you'll need this.
<<give_item "brass key" 1>>
===
Four Commands in a node. The first word inside each is the Command’s name, and the rest are its arguments.

When the dialogue reaches a Command, the Dialogue Runner calls the C# method you’ve connected to it. Once the method has finished, the dialogue carries on.

sequenceDiagram
  participant R as Dialogue Runner
  participant A as Audio code
  participant Rosa as Rosa (Character.cs)
  Note over R: #60;#60;play_sound door_creak#62;#62;
  R->>A: PlaySound("door_creak")
  A-->>R: returns
  Note over R: Shows "Oh! You gave me a fright."
  Note over R: #60;#60;move Rosa 3 0#62;#62;
  R->>Rosa: Move(3, 0)
  Rosa-->>R: returns a YarnTask
  Note over Rosa: Rosa moves for 1 second
  Rosa-->>R: the task finishes
  Note over R: Carries on with #60;#60;wait 1#62;#62;
The first two Commands from the node above. The Dialogue Runner calls a method for each one. The Move method returns a YarnTask, and the dialogue waits until Rosa has finished moving.

Writing a Command

The quickest way to make a Command is to add the [YarnCommand] attribute to a method. The attribute takes the Command’s name in Yarn: [YarnCommand("play_sound")] is <<play_sound>>. If you leave the name out, the method’s name is used, and [YarnCommand] on a method called PlaySound is <<PlaySound>>.

When your C# scripts compile, Yarn Spinner finds every method with the attribute and generates the code that adds it to each Dialogue Runner.

Make the method public, in a public class. A private method still works, but Yarn Spinner has to call it through reflection, which is slower and harder to debug, and you’ll see message YS1001 in the Console when your scripts compile.

There are two kinds of Command, depending on whether the method is static.

Commands that aren’t tied to a GameObject

A static method becomes a Command you can use anywhere:

using Yarn.Unity;

public static class AudioCommands
{
    [YarnCommand("play_sound")]
    public static void PlaySound(string soundName)
    {
        AudioManager.Play(soundName);
    }
}
A static Command. «play_sound door_creak» calls it with soundName set to door_creak.
<<play_sound door_creak>>
Using the static Command in Yarn.

AudioManager stands in for however your game plays sounds. Static Commands suit things the whole game uses, like playing sounds or saving.

Commands on a GameObject

A method that isn’t static belongs to a component. Its class has to be a MonoBehaviour or another kind of Component. In Yarn, the first argument is the name of the GameObject to call it on:

using UnityEngine;
using Yarn.Unity;

public class Character : MonoBehaviour
{
    [YarnCommand("move")]
    public async YarnTask Move(float x, float y)
    {
        var start = transform.position;
        var end = new Vector3(x, y, start.z);
        var elapsed = 0f;
        while (elapsed < 1f)
        {
            elapsed += Time.deltaTime;
            transform.position = Vector3.Lerp(start, end, elapsed);
            await YarnTask.Yield();
        }
    }
}
Line 4 The script goes on the character’s GameObject, which is called Rosa in the scene.
Line 6 The attribute makes this method the <<move>> Command.
Line 7 A Command on a GameObject, because the method isn’t static. In Yarn, the first argument, Rosa, says which GameObject to call it on. x and y come from the other two arguments, converted to float. The dialogue waits until the method has finished, because it’s async and returns a YarnTask.
Lines 12–17 Move the GameObject to the new position over one second, waiting a frame between each step.
Character.cs, on a GameObject called Rosa. «move Rosa 3 0» calls it on Rosa.
<<move Rosa 3 0>>
Calling the Command on the GameObject called Rosa.

If every character in your game has the same script, each one gets a <<move>> Command, and the first argument says which character moves. The GameObject has to be active, because the Dialogue Runner finds it with Unity’s GameObject.Find(). It then looks for the script on that GameObject or its children. If it can’t find the GameObject, or neither it nor its children have the script, it logs an error.

The class can also be one of your own types that has a converter. Then the first argument is passed to the converter instead, and the method is called on the object it returns. If the class is neither, you’ll see error YS1009 when your scripts compile.

Arguments

Arguments are separated by spaces. To pass an argument with a space in it, put it in double quotes: <<give_item "brass key" 1>>.

Each argument is converted to the type of the method’s parameter:

Parameter typeWhat you write in Yarn
stringAny text.
int, float, double and other number typesA number, like 3 or 0.5.
booltrue or false. Writing the parameter’s name means true: for a parameter called wait, <<fade wait>> passes true.
GameObjectThe name of an active GameObject in the scene. The Dialogue Runner finds it and passes it in. With no such GameObject, the Console shows an error and the method isn’t called.
A component type, like Transform or a script of your ownThe name of an active GameObject. The Dialogue Runner finds it, and passes in the first component of that type on it or its children. If there’s none, it’s a Console error and the method isn’t called.
A Yarn enum from the generated variables class, like FoodTypeA case of the enum: FoodType.Apple or .Apple. See Yarn enums.
Your own type, with a converterWhatever text the converter understands. See Your own types.
An array, as the last parameterAny number of arguments, each converted to the array’s element type. See Any number of arguments.
CancellationToken or LineCancellationToken, as the last parameterNothing. The Dialogue Runner passes in a token. See Making the dialogue wait.
How Command arguments are converted to each parameter type.

Parameters with default values can be left out. SaveGame(int slot = 0) can be called as <<save_game 1>> or <<save_game>>. Optional parameters go at the end. A Command that has them can’t take an array, and can’t take a cancellation token.

If there are too few or too many arguments, or an argument can’t be converted, the method isn’t called and you’ll see an error in the Console, which for a wrong count is about the number of arguments.

To use a variable’s value as an argument, put it in curly braces: <<give_item {$reward} 1>>.

Any number of arguments

To let a Command take any number of arguments, make its last parameter a params array. Each argument is converted to the array’s element type, and they arrive together:

[YarnCommand("unlock_cheevo")]
public static void UnlockAchievements(params string[] names)
{
    foreach (var name in names)
    {
        Debug.Log($"Unlocked the {name} achievement!");
    }
}
A Command that unlocks any number of achievements.

<<unlock_cheevo>>, <<unlock_cheevo start_game>> and <<unlock_cheevo start_game pet_the_dog>> all work, with zero, one and two arguments. A Command can have one array, and it has to be the last parameter. An array somewhere else gives you error YS1007. An array of a type Yarn can’t convert to gives you YS1005. A Command with an array can’t have optional parameters, and can’t have a cancellation token.

Yarn enums

If your Yarn Scripts declare an enum, and the Yarn Project generates a typed variables class, that class includes a matching C# enum. Use it as a parameter type, and the Dialogue Runner passes in the right case:

<<enum Achievement>>
    <<case StartTheGame>>
    <<case PetTheDog>>
    <<case FinishTheGame>>
<<endenum>>

<<unlock_cheevo Achievement.StartTheGame>>
An Achievement enum, and a Command that takes one.
[YarnCommand("unlock_cheevo")]
public static void UnlockAchievement(Achievement achievement)
{
    Debug.Log($"Unlocked the {achievement} achievement!");
}
The Command, taking the generated Achievement enum.

<<unlock_cheevo Achievement.StartTheGame>> and the short form <<unlock_cheevo .StartTheGame>> both work. Enums backed by text and enums backed by numbers both work, and enum parameters can be optional or part of an array.

A Command also accepts the enum’s backing value. A variable holding the value, for example one that a Function returned, works without converting it first. The Custom Actions sample does this. If the text matches a case’s name, the name is used before any case’s backing value.

Your own types

A Command can take one of your own types as a parameter, like a tool or an inventory item, if you add a converter for it. A converter is a method marked with [YarnConverter] that turns the text from the Yarn Script into your object:

[YarnConverter(typeof(Tool))]
public static bool TryGetTool(string input, out Tool value)
{
    if (input == "slot1")
    {
        value = GameManager.Player.Inventory[0];
        return true;
    }
    return GameManager.Tools.TryGetValue(input, out value);
}

[YarnCommand("dig")]
public static void Dig(Tool tool)
{
    Debug.Log($"I am digging a hole with {tool}");
    tool.durability--;
}
Line 1 The attribute says which type the converter makes.
Line 2 A converter is public and static, returns bool, and takes a string and an out parameter of the type it makes. Its name can be anything, but something like TryGetTool makes its job clear.
Lines 4–9 The text slot1 means the first tool the player is carrying. Anything else is looked up by name. GameManager stands in for wherever your game keeps its tools.
Lines 12–13 Any Command with a Tool parameter now uses the converter: <<dig slot1>> or <<dig pitchfork>>.
A converter for a Tool type, and a Command that uses it.

The converter returns true if it could make the object, and false if it couldn’t. The type it makes has to be public. Converted types can be used in arrays, and alongside any other parameters, including other converted types. They work for Functions too.

When your scripts compile, a converter that breaks these rules gives you an error between YS1011 and YS1018, which says what’s wrong.

Making the dialogue wait

The dialogue carries on as soon as your method returns. To make it wait until something has finished, like an animation or a sound, have the method return one of these. With each of them, the dialogue waits until the coroutine or async method has finished:

Return typeWhen the dialogue carries on
IEnumeratorThe method is a coroutine. The Dialogue Runner starts it and waits.
CoroutineA coroutine you’ve started yourself with StartCoroutine(). Waits.
YarnTaskAn async method. Waits.
TaskAn async method using .NET’s Task. Waits.
AwaitableAn async method using Unity’s Awaitable, in Unity 2023.1 and later. Waits.
UniTaskAn async method using UniTask, if the UniTask package is installed. Waits.
The return types that make the dialogue wait for a Command.

A Command marked with [YarnCommand] has to return void or one of these. Any other return type gives you error YS1003 when your scripts compile.

The move Command above returns a YarnTask, and the next line only appears once Rosa has arrived. A coroutine works too:

[YarnCommand("wave")]
public IEnumerator Wave()
{
    animator.SetTrigger("Wave");
    yield return new WaitForSeconds(1.5f);
}
A Command in Character.cs that waits for an animation, as a coroutine. animator is an Animator set in the Inspector.

To let the player skip a Command that takes time, make its last parameter a CancellationToken or a LineCancellationToken. You don’t write it in the Yarn Script. The Dialogue Runner passes one in, and it’s cancelled when the player asks to hurry up or move on. A token anywhere but the last parameter gives you error YS1006. Coroutines can’t be cancelled this way. For a skippable Command, make it async. See Waiting in Commands.

For more on writing async Commands, see Async and Cancellation.

Adding Commands from code

You can add a Command to a Dialogue Runner yourself, with any name and any method:

using UnityEngine;
using Yarn.Unity;

public class GameCommands : MonoBehaviour
{
    [SerializeField] DialogueRunner dialogueRunner;

    void Awake()
    {
        dialogueRunner.AddCommandHandler<string, int>("give_item", GiveItem);
    }

    public static void GiveItem(string itemName, int count)
    {
        Inventory.Add(itemName, count);
    }
}
Line 6 The Dialogue Runner. Drag it into this field in the Inspector.
Lines 8–11 Add the Command when the scene starts. The first argument is its name in Yarn. The types in angle brackets are the method’s parameter types, in order.
Line 13 An ordinary method, so <<give_item "brass key" 1>> passes a string and an int. It doesn’t have to be public, but it’s more efficient if it is.
Line 15 Your game’s own code. Inventory stands in for however your game keeps track of items.
Adding a «give_item» Command when the scene starts.
Commands as instance methods

It’s possible to use instance methods (that is, methods without the static keyword) when registering via AddCommandHandler.

We don’t recommend this. It’s slower, and if the object is destroyed and you haven’t removed the Command, the dialogue calls a method on a destroyed object. It’s generally better to use static methods, and if you need access to an instance’s contents, add a way to find the instance yourself like we’re doing in the above code sample. Alternatively, use the [YarnCommand] attribute on your instance methods, and Yarn Spinner will take care of it for you.

When you pass a method by name, list its parameter types in angle brackets, like AddCommandHandler<string, int>. Passing a lambda to AddCommandHandler() is deprecated, and you’ll see message YS1021 when your scripts compile. Pass a named method instead.

The method can return any of the types in Making the dialogue wait, and the dialogue waits for it in the same way.

To remove a Command, call dialogueRunner.RemoveCommandHandler("give_item").

Command names can’t have spaces in them. The Dialogue Runner logs an error and ignores a Command you add with a space in its name. It does the same for one with the same name as a Command that’s already been added from code. If the name belongs to a [YarnCommand] method or a built-in Command like wait, yours is ignored without an error.

Choosing between the attribute and code

Both ways do the same job.

[YarnCommand] works well for methods on your characters and objects, like moving or animating them, where the Command sits next to the code it runs. For Commands that affect the whole game, like loading a scene or unlocking an achievement, AddCommandHandler() puts them all in one place, where you can see every one at once.

How attributed Commands are found

Yarn Spinner finds methods marked with [YarnCommand] when your C# scripts compile, not while the game runs. It generates code that adds them to every Dialogue Runner the first time the Dialogue Runner needs a Command.

This is controlled by Generate linkings for Functions and Commands in Yarn Spinner’s Project Settings. It’s on by default. If you turn it off, methods marked with [YarnCommand] aren’t added, and you have to add every Command yourself with AddCommandHandler().

Built-in Commands

Two Commands are always available:

CommandWhat it does
<<wait 2>>Waits for the number of seconds you give it before the dialogue carries on. With UniTask or Awaitable, it uses scaled time and stops counting while Time.timeScale is 0. With System.Threading.Tasks.Task, it counts real time. The player can skip it.
<<stop>>Ends the dialogue immediately.
Commands that are always available.

Seeing your Commands

Choose WindowYarn SpinnerCommands and Functions... to open the Yarn Actions window. It lists the Commands you’ve marked with [YarnCommand], along with wait and stop, and shows how to call each one. For the move Command above, it shows <<move target (Character) x (number) y (number)>>.

Type in the search field at the top to narrow the list. Commands you add with AddCommandHandler() aren’t listed, because they’re only added while the game runs.

The Yarn Actions window, with its search field and a list of Commands, including wait, stop and a Command on a GameObject, each showing how to call it.
Commands in the Yarn Actions window.

When a Command isn’t found

If the dialogue reaches a Command that isn’t connected to anything, the Dialogue Runner logs a message and carries on with the next line. The message is Encountered undispatched command <<play_sound door_creak>> if your game has added any Commands from code, and the error The command dispatcher has not been configured to handle play_sound if it hasn’t. Check the Console if a Command doesn’t seem to do anything, because a misspelt Command is skipped.

To handle Commands yourself, without registering each one, write a Presenter with a RunCommand() method. The Dialogue Runner calls it on every Presenter for every Command, before the Command runs, whether or not anything else handles it. DialogueRunner.SplitCommandText() splits the Command’s text into its name and arguments. See Reacting to dialogue.

Autocomplete in VS Code

The Yarn Spinner extension for VS Code can suggest your Commands as you type, and warn you about ones it doesn’t know. It reads them from the .ysls.json file that Yarn Spinner writes when your C# scripts compile. See The .ysls.json file.

Two attributes from the Yarn.Unity.Attributes namespace change what VS Code suggests for a string parameter:

  • [YarnNodeParameter] suggests the names of the nodes in your project.
  • [YarnEnumParameter("Mood")] suggests the cases of the enum called Mood from your Yarn Scripts.
[YarnCommand("jump_to")]
public static void JumpTo([YarnNodeParameter] string nodeName)
{
    Debug.Log($"Jumping to {nodeName}");
}
A Command whose argument VS Code fills in with node names.

These attributes only change the suggestions. The argument is still passed to your method as text, whatever it is. For a parameter that really is an enum, use the generated enum type instead, and VS Code suggests its cases too.

If a Command can’t work, for example because of a parameter type Yarn can’t pass in, Yarn Spinner marks it in the .ysls.json file, and VS Code shows it struck through with a warning. The Console shows the same error when your scripts compile.

For a scene that uses Commands and Functions together, see Putting It Together.

Next step Functions Getting values from your game to use in lines and conditions.