Functions
A Function lets a Yarn Script ask your game for a value, like how many coins the player has, or whether they’re carrying a key. You call it by name, with any arguments in brackets, and your game sends back the answer:
title: FunctionsDemo
---
<<if has_item("brass key")>>
Rosa: Good, you've got the key.
<<else>>
Rosa: You'll need a key to get up the stairs.
<<endif>>
<<set $coin_total to coin_count()>>
Rosa: You've got {$coin_total} coins.
===Where a Command tells your game to do something, a Function asks it a question. The dialogue uses the answer and carries on.
sequenceDiagram
participant R as Dialogue Runner
participant G as Your game code
Note over R: #60;#60;if has_item("brass key")#62;#62;
R->>G: HasItem("brass key")
G-->>R: returns false
Note over R: Shows "You'll need a key to get up the stairs."
Note over R: #60;#60;set $coin_total to coin_count()#62;#62;
R->>G: CoinCount()
G-->>R: returns 15
Note over R: Shows "You've got 15 coins."Using Functions in Yarn
You can use a Function anywhere Yarn expects a value:
- in a condition:
<<if has_item("brass key")>>, - in a
<<set>>:<<set $coin_total to coin_count()>>, - in an expression with other values:
<<if coin_count() >= 10>>.
Put text arguments in double quotes, like "brass key". Numbers, true and false, and variables go in as they are: has_item($chosen_item).
A Function can go directly inside a line, like Rosa: You've got {coin_count()} coins. When your C# scripts compile, Yarn Spinner writes the Functions you’ve marked with [YarnFunction] into a .ysls.json file, including what each one returns, and the Yarn compiler reads it. The Yarn Project’s Definitions list has to include these files. See The .ysls.json file.
In a Yarn Project made with Yarn Spinner 3.3, the compiler has to know about every Function you use. If it doesn’t, you’ll see “no declaration found” when the project imports. In a project made before Yarn Spinner 3.3, that’s a warning, and the compiler works out what the Function returns from how you use it.
Writing a Function
Functions marked with an attribute
Add the [YarnFunction] attribute to a method, and give the attribute the Function’s name in Yarn. A static method can be called from anywhere:
using Yarn.Unity;
public static class TextFunctions
{
[YarnFunction("shout")]
public static string Shout(string text)
{
return text.ToUpperInvariant();
}
}If you leave the name out, the method’s name is used. Yarn Spinner finds these methods when your scripts compile, in the same way as it finds Commands, and adds them to every Dialogue Runner. See How attributed Commands are found.
Make it public, in a public class. A private method still works, but it’s called through reflection, which is slower, and you’ll see message YS1001 in the Console when your scripts compile.
Functions on a GameObject
A [YarnFunction] method that isn’t static belongs to a component. In Yarn, the first argument is the name of the GameObject to call it on, in double quotes:
using UnityEngine;
using Yarn.Unity;
public class Health : MonoBehaviour
{
public int hitPoints = 10;
[YarnFunction("health")]
public int GetHealth()
{
return hitPoints;
}
}Alice has {health("Alice")} hit points, and Bob has {health("Bob")}.The GameObject has to be active, because the Dialogue Runner finds it with GameObject.Find(). It then looks for the component on it or its children, the same as for a Command on a GameObject. The class can also be one of your own types with a converter, and then the first argument goes to the converter. If the class is neither, you’ll see error YS1009 when your scripts compile.
Functions that use your game’s state
A static method can’t read the fields on a component, like an inventory. For a Function that needs to, add a way for the function to access an instance.
using System.Collections.Generic;
using UnityEngine;
using Yarn.Unity;
public class PlayerState : MonoBehaviour
{
[SerializeField] DialogueRunner dialogueRunner;
readonly List<string> inventory = new List<string> { "lantern" };
int coins = 15;
static private PlayerState Instance => FindAnyObjectByType<PlayerState>();
void Awake()
{
dialogueRunner.AddFunction<string, bool>("has_item", HasItem);
dialogueRunner.AddFunction<int>("coin_count", CoinCount);
}
public static bool HasItem(string itemName)
{
return Instance.inventory.Contains(itemName);
}
public static int CoinCount()
{
return Instance.coins;
}
}static methods can’t access these directly.static methods can use to find an instance of the PlayerState class to work with.has_item("brass key") in Yarn calls this. It returns a bool, so it can be used in an <<if>>.coin_count() returns a number.It’s also possible to use instance methods (that is, methods without the static keyword) when registering via AddFunction.
We don’t recommend this. It’s slower, and if the object is destroyed and you haven’t removed the Function, 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.
When you pass a method by name, list its parameter types and then its return type in angle brackets, like AddFunction<string, bool>. Passing a lambda to AddFunction() is deprecated, and you’ll see message YS1021 when your scripts compile. Pass a named method instead.
To remove a Function, call dialogueRunner.RemoveFunction("has_item").
Two Functions can’t have the same name, and a Function can’t use the name of a built-in one. If you add a Function with a space in its name, or with a name that’s already been added from code, the Dialogue Runner logs an error and ignores it. If the name belongs to a [YarnFunction] method, yours is ignored without an error.
Values going in and out
A Function has to return one of the kinds of value Yarn understands:
| Return type | In Yarn |
|---|---|
bool | true or false. |
int, float, double and other number types | A number. |
string | Text. |
A Function marked with [YarnFunction] that returns anything else gives you error YS1004 when your scripts compile. A Function can’t return void.
Arguments are converted to the types of the method’s parameters. A Yarn number becomes an int, float or whichever number type the parameter has, and true and false become a bool. Parameters with default values can be left out.
A parameter can be a Yarn enum from the generated variables class, like FoodType. Yarn passes the enum’s value, and your method gets the matching case. See Yarn enums. A parameter can also be one of your own types, if it has a converter.
A Function can’t return a Yarn enum. Return the enum’s backing value instead, like "apple", as a string or number. The generated class gives each enum a GetBackingValue() method for this. A Command accepts the backing value as an enum argument, so you can pass it straight in. The Custom Actions sample does this.
To take any number of arguments, make the last parameter a params array, as for Commands.
Functions that wait
A Function can take as long as it needs, for example to animate a dice roll before returning it, or to let the player pick an item. Make it async, and return the generic form of a task, with the type of the value it returns: YarnTask<int>, Task<int>, Awaitable<int> or UniTask<int>. The dialogue pauses until it returns:
[YarnFunction("evil_d6")]
public static async YarnTask<int> EvilDice()
{
var roll = UnityEngine.Random.Range(1, 7);
await AnimateDiceToFace(roll);
if (roll == 6)
{
await AnimateDiceToFace(5);
roll = 5;
}
return roll;
}AnimateDiceToFace() stands in for your own animation code. A Function can’t be a coroutine, because a coroutine can’t return a value.
If the last parameter 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 give up early. Use a CancellationToken, not a LineCancellationToken. Hurrying up doesn’t apply to a Function, and a LineCancellationToken parameter gives you warning YS1026 when your scripts compile. See Async and Cancellation.
Built-in Functions
These Functions are always available:
| Function | What it returns |
|---|---|
visited("NodeName") | true if the node has been run before. |
visited_count("NodeName") | How many times the node has been run. |
random() | A random number between 0 and 1. |
random_range(1, 6) | A random whole number from the first number to the second, including both. |
dice(6) | A random whole number from 1 to the number you give it, like rolling a die. |
round(n), floor(n), ceil(n) | The number rounded to the nearest whole number, down, or up. |
min(a, b), max(a, b) | The smaller or larger of two numbers. |
For maths there are also random_range_float, round_places, inc, dec, decimal and int. For converting between types there are string, number and bool. For formatting numbers there are format and format_invariant.
Autocomplete in VS Code
The Yarn Spinner extension for VS Code suggests your Functions as you type, along with what they return. It reads them from the .ysls.json file that Yarn Spinner writes when your C# scripts compile. A Function that can’t work, such as one that returns a type Yarn can’t use, is shown struck through with a warning. See The .ysls.json file.
For a scene that uses Commands and Functions together, see Putting It Together.