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, Yarn Spinner for Godot GDScript and Yarn Spinner for Unreal Engine (work in progress) are on /docs/ (the new docs site).

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.
===
Two Functions in a node. has_item decides which line Rosa says, and coin_count’s value is shown in a line.

The dialogue uses the value and carries on. To have your game do something, use a Command.

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: _has_item("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: _coin_count()
  G-->>R: returns 15
  Note over R: Shows "You've got 15 coins."
The Dialogue Runner calls the Function’s method in your game, and the value it returns is used in the Yarn Script.
Functions in a scene. The panel in the top left lists each Function call and the value it returned, and Rosa's lines use those values.

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 the Yarn Project is imported, the addon finds your Functions and tells the compiler what each one returns. The compiler uses that to work out how to show the value.

If the addon can’t find a Function’s return type, a Function used directly inside a line won’t compile, and you’ll see “Can’t determine the type of the expression”. That happens when:

  • the addon can’t find the Function’s script, because it isn’t in the Yarn Project’s folder or in a scene that uses the Yarn Project, or it’s outside the folder set in the Ysls Scan Path import option (see The .ysls.json file),
  • the Function’s method doesn’t say what it returns, like func _coin_count(): instead of func _coin_count() -> int:, or it returns a Signal, or it’s a lambda,
  • the Function is added by an addon, which the plugin skips unless you list it (see Commands and Functions in an addon),
  • the Yarn Project’s Generate Ysls import option is off and the project is compiled with ysc instead of the built-in compiler. The built-in compiler gets your Functions’ types whether the option is on or off.

In a version 5 Yarn Project, the compiler has to know about every Function, wherever it’s used. For a Function the plugin can’t find a return type for, you’ll see “no declaration found” instead, and the error says what to change.

Fix whichever applies, or store the value in a variable first and put the variable in the line:

<<set $coin_total to coin_count()>>
Rosa: You've got {$coin_total} coins.
Storing coin_count()’s value in $coin_total before Rosa’s line uses it.

Writing a Function

Functions the Dialogue Runner finds by itself

Give a static method a name that starts with _yarn_function_, and the rest of the name is the Function’s name in Yarn:

static func _yarn_function_shout(text: String) -> String:
	return text.to_upper()
A static Function that returns its text in capitals.

The Dialogue Runner finds these methods in the same places it finds Commands: in scripts with a class_name, in scripts attached to nodes in the running scene, and in autoloads. See Where the Dialogue Runner looks.

A static method can be called from anywhere. A method in an autoload can be either.

Functions on a node

A _yarn_function_ method that isn’t static belongs to the script on a node. In Yarn, the first argument is the name of the node to call it on, in double quotes:

@export var hit_points := 10


func _yarn_function_health() -> int:
	return hit_points
A Function on a character’s script, on nodes called Alice and Bob.
Alice has {health("Alice")} hit points, and Bob has {health("Bob")}.
Asking two characters for their health.

The Dialogue Runner finds the node the same way as for a Command on a node. It then checks that the node, or one of its children, has the script. If there’s no node with that name, or it doesn’t have the script, the Dialogue Runner logs an error and stops the dialogue.

If the script’s class has a converter, the first argument goes to the converter instead, and the method is called on the object it returns.

The .ysls.json lists the node as the Function’s first parameter, and VS Code expects a name there.

Functions that use your game’s state

A static method can’t read the variables on a node, like an inventory. For a Function that needs to, add it to the Dialogue Runner with add_function():

@export var dialogue_runner: YarnDialogueRunner

var _inventory: Array[String] = ["lantern"]
var _coins := 15


func _ready():
	dialogue_runner.add_function("has_item", _has_item)
	dialogue_runner.add_function("coin_count", _coin_count)


func _has_item(item_name: String) -> bool:
	return item_name in _inventory


func _coin_count() -> int:
	return _coins
Line 1 The Dialogue Runner, set in the Inspector.
Lines 3–4 The game state the Functions read. A static method couldn’t see these.
Lines 7–9 Add both Functions when the scene starts. The first argument is each one’s name in Yarn.
Lines 12–13 has_item("brass key") in Yarn calls this. It returns a bool, which an <<if>> can use.
Lines 16–17 coin_count() returns a number.
Adding two Functions that read the player’s inventory and coins.

Pass a named method, like _has_item, so the Dialogue Runner can see its parameters. A lambda has no parameter types, and its arguments aren’t converted. Adding a Function with a lambda still works, but it’s deprecated, and the Dialogue Runner logs a warning. If you do pass a lambda, give the number of arguments it takes as a third argument: dialogue_runner.add_function("double", func(n): return n * 2, 1).

To remove a Function, call dialogue_runner.remove_function("has_item"). To add a Function to every Dialogue Runner in your game, call YarnSpinner.register_function(), with the same arguments, before the Dialogue Runners start.

Two Functions can’t have the same name. If a second one uses a name that’s already taken, the Dialogue Runner logs an error and ignores it.

Values going in and out

A Function has to return one of the kinds of value Yarn understands:

Return typeIn Yarn
booltrue or false.
int or floatA number.
StringText.
What a Function can return.

If a Function returns something else, or returns nothing, the Dialogue Runner logs an error and stops the dialogue.

Arguments are converted to the types of the method’s parameters. A Yarn number becomes an int or float, and true and false become a bool. A parameter without a type gets the value as it is. Parameters with default values can be left out.

A parameter can be a Yarn enum from the generated variables class, like MyVariables.FoodType. Yarn passes the enum’s value, and your method gets the matching case, such as MyVariables.FoodType.APPLE. See Yarn enums.

A Function can’t return a Yarn enum. If its return type is an enum, the Dialogue Runner logs an error and stops the dialogue. Return the enum’s value instead, like "apple", with a String or number return type. You can store it in a variable declared as text and compare it with string($your_enum_variable). The Custom Actions sample does this.

To take any number of arguments, end the method’s parameters with ... and a name. The extra arguments arrive as an Array, and the built-in plural() and ordinal() work this way:

func _total(...values: Array) -> float:
	var sum := 0.0
	for value in values:
		sum += value
	return sum
A Function that adds up any number of values.

total(1, 2, 3) returns 6. The ... parameter has to be the last one.

GDScript can’t give a ... parameter a type. The addon can’t tell the compiler what the extra arguments are, and leaves the Function undeclared. In a version 4 Yarn Project, the compiler works out the types from how you call it, but only outside lines. In a version 5 Yarn Project, every Function has to be declared. Add one to a .ysls.json file in the project’s definitions, giving the extra arguments a type with "isParamsArray": true. The built-in plural() and ordinal() are already declared.

A parameter can also be one of your own types, like an inventory item, if you add a converter for it. The text from the Yarn Script goes to the converter, and your method gets what it returns. See Your own types.

Functions that wait

A Function can take as long as it needs, for example to let the player pick an item. Use await in the method, and give it the type of the value it ends up returning. The dialogue pauses until it returns:

func _ready():
	dialogue_runner.add_function("pick_item", _pick_item)


func _pick_item() -> String:
	var item = await inventory_menu.item_chosen
	return item.name
A pick_item Function that waits for the player to choose.
<<set $chosen to pick_item()>>
Rosa: A {$chosen}? Thanks!
Using pick_item in a Yarn Script.

Write the return type the value will have, like -> String, not -> Signal. Returning a Signal works while the game runs, but the compiler can’t tell what it will carry, and a version 5 Yarn Project won’t compile calls to it.

Functions used in smart variables or in when: headers still have to return straight away. If one of those waits, the Dialogue Runner logs an error.

If the last parameter of a Function is a YarnCancellationToken, the Dialogue Runner passes one in. A Function that’s waiting can use it to give up early, because it’s cancelled when the dialogue stops. request_hurry_up() and request_next_content() don’t affect it. The exception is a Function called while a Command is running, which shares the Command’s token. See Async and Cancellation.

If a Function gets the wrong number of arguments, or one can’t be converted, the Dialogue Runner logs an error and stops the dialogue.

Built-in Functions

These Functions are always available:

FunctionWhat 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.
Some of the built-in Functions.

For maths there are random_range_float, round_places, inc, dec, decimal, int, abs, sign, clamp, lerp, inverse_lerp, smoothstep, pow, sqrt, wrap and mod. For converting between types there are string, number and bool. For text there are format, format_invariant, length, uppercase, lowercase, first_letter_caps, plural and ordinal. has_any_content("GroupName") checks whether a node group has a node whose conditions pass.

These built-in Functions are only in Yarn Spinner for Godot: abs, sign, clamp, lerp, inverse_lerp, smoothstep, pow, sqrt, wrap, mod, length, uppercase, lowercase, plural, ordinal, has_any_content and first_letter_caps. A Yarn Script that uses them won’t compile in Yarn Spinner for Unity, or in other tools that don’t have them. If you share your Yarn Scripts with another engine, don’t use them.

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 project’s .ysls.json file, which the addon writes for you. The file includes Functions you add with add_function(). This covers add_function() called on a Dialogue Runner variable, and called on its own in a script that extends the Dialogue Runner. The file also lists the built-in Functions above that only Yarn Spinner for Godot has, which stops VS Code marking them as unknown. See The .ysls.json file.

The demo scene

GameNode2D
BackgroundColorRect
FloorColorRect
DoorColorRect
LampColorRect
GlowColorRect
RosaNode2D
BodyColorRect
NameLabel
YarnDialogueRunner
UICanvasLayer
CallLogPanelPanelContainer
CallLogRichTextLabel
InventoryPanelPanelContainer
InventoryLabel
YarnLinePresenter
The demo scene. Game’s script has the Functions.
title: FunctionsDemo
---
<<declare $lamp_days = 0>>
<<set $lamp_days to days_since_lamp_lit()>>
Rosa: The lamp's been out for {$lamp_days} days.
<<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>>
<<declare $coin_total = 0>>
<<set $coin_total to coin_count()>>
Rosa: You've got {$coin_total} coins.
<<if coin_count() >= 10>>
    Rosa: That's enough to buy oil for the lamp.
<<endif>>
<<declare $sign_text = "">>
<<set $sign_text to shout("keep out")>>
Rosa: The sign on the door says "{$sign_text}".
===
The Yarn Script. Each Function’s value is stored in a variable before it’s shown in a line.
extends Node2D

@export var dialogue_runner: YarnDialogueRunner
@export var call_log: RichTextLabel
@export var inventory_label: Label

var _inventory: Array[String] = ["lantern"]
var _coins := 15

static var _log: RichTextLabel


func _ready():
	_log = call_log
	dialogue_runner.add_function("days_since_lamp_lit", _days_since_lamp_lit)
	dialogue_runner.add_function("has_item", _has_item)
	dialogue_runner.add_function("coin_count", _coin_count)
	_update_inventory()


static func _log_function(call_text: String, result: Variant) -> void:
	var shown := '"%s"' % result if result is String else str(result)
	_log.append_text("[color=#7fc4e8]Function[/color] %s → %s\n" % [call_text, shown])


func _update_inventory() -> void:
	var text := "Inventory\n"
	for item in _inventory:
		text += "• " + item + "\n"
	text += "• %d coins" % _coins
	inventory_label.text = text


# Functions added in _ready

func _days_since_lamp_lit() -> int:
	var days := 12
	_log_function("days_since_lamp_lit()", days)
	return days


func _has_item(item_name: String) -> bool:
	var result := item_name in _inventory
	_log_function('has_item("%s")' % item_name, result)
	return result


func _coin_count() -> int:
	_log_function("coin_count()", _coins)
	return _coins


# A Function the Dialogue Runner finds by itself

static func _yarn_function_shout(text: String) -> String:
	var result := text.to_upper()
	_log_function('shout("%s")' % text, result)
	return result
Lines 3–5 Nodes in the scene, set in the Inspector.
Lines 7–8 The game state the Functions read.
Lines 10 & 14 The log panel, kept in a static variable so the static Function can write to it too. This is only for the demo.
Lines 15–17 Add three Functions. shout is static and named _yarn_function_shout, and the Dialogue Runner finds it by itself.
Lines 21–23 Write each call and its result to the panel in the top left. This is only for the demo.
Lines 26–31 Show the inventory and coins in the top right.
Lines 36–39 days_since_lamp_lit() returns a number.
Lines 42–45 has_item() returns a bool.
Lines 48–50 coin_count() returns the number of coins.
Lines 55–58 shout() returns its text in capitals. Being static, it can’t read this node’s variables.
The script on the Game node.
Next step Putting It Together A small scene that uses Commands and Functions together.