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>>
===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;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);
}
}<<play_sound door_creak>>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();
}
}
}<<move>> Command.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.<<move Rosa 3 0>>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 type | What you write in Yarn |
|---|---|
string | Any text. |
int, float, double and other number types | A number, like 3 or 0.5. |
bool | true or false. Writing the parameter’s name means true: for a parameter called wait, <<fade wait>> passes true. |
GameObject | The 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 own | The 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 FoodType | A case of the enum: FoodType.Apple or .Apple. See Yarn enums. |
| Your own type, with a converter | Whatever text the converter understands. See Your own types. |
| An array, as the last parameter | Any number of arguments, each converted to the array’s element type. See Any number of arguments. |
CancellationToken or LineCancellationToken, as the last parameter | Nothing. The Dialogue Runner passes in a token. See Making the dialogue wait. |
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!");
}
}<<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>>[YarnCommand("unlock_cheevo")]
public static void UnlockAchievement(Achievement achievement)
{
Debug.Log($"Unlocked the {achievement} achievement!");
}<<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--;
}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.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.Tool parameter now uses the converter: <<dig slot1>> or <<dig pitchfork>>.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 type | When the dialogue carries on |
|---|---|
IEnumerator | The method is a coroutine. The Dialogue Runner starts it and waits. |
Coroutine | A coroutine you’ve started yourself with StartCoroutine(). Waits. |
YarnTask | An async method. Waits. |
Task | An async method using .NET’s Task. Waits. |
Awaitable | An async method using Unity’s Awaitable, in Unity 2023.1 and later. Waits. |
UniTask | An async method using UniTask, if the UniTask package is installed. Waits. |
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);
}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);
}
}<<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.Inventory stands in for however your game keeps track of items.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:
| Command | What 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. |
Seeing your Commands
Choose 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.

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 calledMoodfrom your Yarn Scripts.
[YarnCommand("jump_to")]
public static void JumpTo([YarnNodeParameter] string nodeName)
{
Debug.Log($"Jumping to {nodeName}");
}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.