Yarn Spinner 3 is now available!
Buy Now
LogoLogo
HomepageDiscordItchPatreonAsset Store
Yarn Spinner 2.0
Yarn Spinner 2.0
  • ⭐Start Here
  • Writing Your Dialogue
    • ⌨️Editing with VS Code
      • Installing the Extension
      • Writing Yarn in VS Code
    • ✍️Writing in Yarn
      • Nodes, Lines, and Options
      • Variables
      • Flow Control
      • Markup
      • Commands
      • Functions
    • 🪄Upgrading Yarn Scripts
  • Working With Unity
    • Overview
    • 📦Installation
    • ⚡Quick Start
    • 📥Importing Yarn Files
      • Yarn Scripts
      • Yarn Projects
    • 🧱Components
      • Dialogue Runner
      • Dialogue Views
        • Line View
        • Options List View
        • Option View
      • Variable Storage
        • In-Memory Variable Storage
        • Custom Variable Storage Components
      • Line Provider
        • Text Line Provider
        • Audio Line Provider
    • 🤖Commands and Functions
    • 🗺️Localizations and Assets
  • Unity Sample Projects
    • 🛠️Choose-Your-Path Game
    • 🛠️Choose-Your-Path Game with Visuals
    • 🛠️NPC Dialogue Game
  • Guides
    • 🗃️Yarn Variables and Variable Storage
  • About
    • The Team
    • GitHub Repositories
    • Community Projects
  • API Documentation
    • C#
      • Yarn Namespace
        • BuiltinTypes
          • Any
          • Boolean
          • Number
          • String
          • TypeMappings
        • Command
          • Text
        • CommandHandler
        • Dialogue
          • DefaultStartNodeName
          • Dialogue(Yarn.IVariableStorage)
          • AddProgram(Program)
          • Continue()
          • ExpandSubstitutions(string,IList<string>)
          • GetStringIDForNode(string)
          • GetTagsForNode(string)
          • NodeExists(string)
          • ParseMarkup(string)
          • SetNode(string)
          • SetProgram(Program)
          • SetSelectedOption(int)
          • Stop()
          • UnloadAll()
          • CommandHandler
          • CurrentNode
          • DialogueCompleteHandler
          • IsActive
          • LanguageCode
          • Library
          • LineHandler
          • LogDebugMessage
          • LogErrorMessage
          • NodeCompleteHandler
          • NodeNames
          • NodeStartHandler
          • OptionsHandler
          • PrepareForLinesHandler
          • VariableStorage
        • DialogueCompleteHandler
        • DialogueException
        • FunctionType
          • Description
          • Methods
          • Name
          • Parameters
          • Parent
          • ReturnType
        • IType
          • Description
          • Methods
          • Name
          • Parent
        • IVariableStorage
          • Clear()
          • SetValue(string,bool)
          • SetValue(string,float)
          • SetValue(string,string)
          • TryGetValue(string,T)
        • Library
          • DeregisterFunction(string)
          • FunctionExists(string)
          • GetFunction(string)
          • ImportLibrary(Library)
          • RegisterFunction(string,Delegate)
          • RegisterFunction(string,Func<TResult>)
          • RegisterFunction(string,Func<T1, TResult>)
          • RegisterFunction(string,Func<T1, T2, TResult>)
          • RegisterFunction(string,Func<T1, T2, T3, TResult>)
          • RegisterFunction(string,Func<T1, T2, T3, T4, TResult>)
          • RegisterFunction(string,Func<T1, T2, T3, T4, T5, TResult>)
        • Line
          • ID
          • Substitutions
        • LineHandler
        • Logger
        • MemoryVariableStore
          • Clear()
          • SetValue(string,bool)
          • SetValue(string,float)
          • SetValue(string,string)
          • TryGetValue(string,T)
        • Node
          • ToString()
          • Instructions
          • Labels
          • Name
          • SourceTextStringID
          • Tags
        • NodeCompleteHandler
        • NodeStartHandler
        • OptionSet
          • Options
          • Option
            • DestinationNode
            • ID
            • IsAvailable
            • Line
        • OptionsHandler
        • PrepareForLinesHandler
        • Program
          • Combine(Program[])
          • ToString()
          • InitialValues
          • Name
          • Nodes
      • Yarn.Markup Namespace
        • MarkupAttribute
          • ToString()
          • Length
          • Name
          • Position
          • Properties
        • MarkupParseException
        • MarkupParseResult
          • Attributes
          • Text
          • DeleteRange(MarkupAttribute)
          • TextForAttribute(MarkupAttribute)
          • TryGetAttributeWithName(string,MarkupAttribute)
        • MarkupProperty
          • Name
          • Value
        • MarkupValue
          • ToString()
          • BoolValue
          • FloatValue
          • IntegerValue
          • StringValue
          • Type
        • MarkupValueType
          • Bool
          • Float
          • Integer
          • String
      • Yarn.Compiler Namespace
        • CompilationJob
          • CompilationType
          • Files
          • Library
          • VariableDeclarations
          • CreateFromFiles(IEnumerable<string>,Library)
          • CreateFromFiles(string[])
          • CreateFromString(string,string,Library)
          • File
            • FileName
            • Source
          • Type
            • DeclarationsOnly
            • FullCompilation
            • StringsOnly
        • CompilationResult
          • ContainsImplicitStringTags
          • Declarations
          • Diagnostics
          • FileTags
          • Program
          • StringTable
        • Compiler
          • Compile(CompilationJob)
          • FlattenParseTree(IParseTree)
          • GetDocumentComments(CommonTokenStream,ParserRuleContext,bool)
          • GetLineIDForNodeName(string)
        • Declaration
          • ExternalDeclaration
          • Declaration()
          • CreateVariable(string,Yarn.IType,IConvertible,string)
          • Equals(object)
          • GetHashCode()
          • ToString()
          • DefaultValue
          • Description
          • IsImplicit
          • Name
          • SourceFileLine
          • SourceFileName
          • SourceNodeLine
          • SourceNodeName
          • Type
        • Diagnostic
          • Column
          • Context
          • FileName
          • Line
          • Message
          • Severity
          • Diagnostic(string,ParserRuleContext,string,DiagnosticSeverity)
          • Diagnostic(string,int,int,string,DiagnosticSeverity)
          • Diagnostic(string,string,DiagnosticSeverity)
          • Diagnostic(string,DiagnosticSeverity)
          • Equals(object)
          • GetHashCode()
          • ToString()
          • DiagnosticSeverity
            • Error
            • Info
            • Warning
        • FileParseResult
          • FileParseResult(string,IParseTree,CommonTokenStream)
          • Equals(object)
          • GetHashCode()
          • Name
          • Tokens
          • Tree
        • IndentAwareLexer
          • IndentAwareLexer(ICharStream,TextWriter,TextWriter)
          • NextToken()
          • Warnings
          • Warning
            • Message
            • Token
        • StringInfo
          • fileName
          • isImplicitTag
          • lineNumber
          • metadata
          • nodeName
          • text
          • ToString()
        • Utility
          • AddTagsToLines(string,ICollection<string>)
          • GenerateYarnFileWithDeclarations(IEnumerable<Yarn.Compiler.Declaration>,string,IEnumerable<string>,I
          • ParseSource(string)
      • Yarn.Compiler.Upgrader Namespace
        • LanguageUpgrader
          • Upgrade(UpgradeJob)
        • OrderedSet
          • OrderedSet()
          • OrderedSet(IEqualityComparer<T>)
          • Add(T)
          • Add(IEnumerable<T>)
          • Clear()
          • Contains(T)
          • CopyTo(T[],int)
          • GetEnumerator()
          • Remove(T)
          • Count
          • IsReadOnly
        • TextReplacement
          • Comment
          • OriginalText
          • ReplacementText
          • Start
          • StartLine
          • OriginalLength
          • ReplacementLength
        • UpgradeJob
          • Files
          • UpgradeType
          • UpgradeJob(UpgradeType,IEnumerable<CompilationJob.File>)
        • UpgradeResult
          • Files
          • Diagnostics
          • OutputFile
            • Diagnostics
            • IsNewFile
            • OriginalSource
            • Path
            • Replacements
            • UpgradedSource
        • UpgradeType
          • Version1to2
      • Yarn.Unity Namespace
        • AssemblyExtensions
          • GetLoadableTypes(Assembly)
        • AudioLineProvider
          • AssetLoadCompleteAction
          • audioLanguage
          • completedLoadOperations
          • pendingLoadOperations
          • GetLocalizedLine(Line)
          • PrepareForLines(IEnumerable<string>)
          • LinesAvailable
        • AudioLocalizedLine
          • AudioClip
        • CharacterColorView
          • RunLine(LocalizedLine,Action)
          • CharacterColorData
            • characterName
            • displayColor
        • Culture
          • DisplayName
          • Name
          • NativeName
        • Cultures
          • GetCulture(string)
          • GetCultures()
          • HasCulture(string)
        • DialogueCharacterNameView
          • onDialogueStarted
          • onNameNotPresent
          • onNameUpdate
          • DialogueStarted()
          • RunLine(LocalizedLine,Action)
        • DialogueOption
          • DialogueOptionID
          • IsAvailable
          • Line
          • TextID
        • DialogueRunner
          • automaticallyContinueLines
          • dialogueViews
          • lineProvider
          • onCommand
          • onDialogueComplete
          • onNodeComplete
          • onNodeStart
          • runSelectedOptionAsLine
          • startAutomatically
          • startNode
          • verboseLogging
          • yarnProject
          • AddCommandHandler(string,System.Action)
          • AddCommandHandler(string,System.Func<Coroutine>)
          • AddCommandHandler(string,System.Action<T1>)
          • AddCommandHandler(string,System.Func<T1, Coroutine>)
          • AddCommandHandler(string,System.Action<T1, T2>)
          • AddCommandHandler(string,System.Func<T1, T2, Coroutine>)
          • AddCommandHandler(string,System.Action<T1, T2, T3>)
          • AddCommandHandler(string,System.Func<T1, T2, T3, Coroutine>)
          • AddCommandHandler(string,System.Action<T1, T2, T3, T4>)
          • AddCommandHandler(string,System.Func<T1, T2, T3, T4, Coroutine>)
          • AddCommandHandler(string,System.Action<T1, T2, T3, T4, T5>)
          • AddCommandHandler(string,System.Func<T1, T2, T3, T4, T5, Coroutine>)
          • AddCommandHandler(string,System.Action<T1, T2, T3, T4, T5, T6>)
          • AddCommandHandler(string,System.Func<T1, T2, T3, T4, T5, T6, Coroutine>)
          • AddFunction(string,System.Func<TResult>)
          • AddFunction(string,System.Func<TResult, T1>)
          • AddFunction(string,System.Func<TResult, T1, T2>)
          • AddFunction(string,System.Func<TResult, T1, T2, T3>)
          • AddFunction(string,System.Func<TResult, T1, T2, T3, T4>)
          • AddFunction(string,System.Func<TResult, T1, T2, T3, T4, T5>)
          • AddFunction(string,System.Func<TResult, T1, T2, T3, T4, T5, T6>)
          • Clear()
          • GetTagsForNode(String)
          • NodeExists(string)
          • OnViewUserIntentNextLine()
          • RemoveCommandHandler(string)
          • RemoveFunction(string)
          • ResetDialogue(string)
          • SetDialogueViews(DialogueViewBase[])
          • SetInitialVariables(bool)
          • SetProject(YarnProject)
          • SplitCommandText(string)
          • StartDialogue(string)
          • Stop()
          • CurrentNodeName
          • Dialogue
          • IsDialogueRunning
          • VariableStorage
          • StringUnityEvent
        • DialogueViewBase
          • DialogueComplete()
          • DialogueStarted()
          • DismissLine(Action)
          • NodeComplete(string,Action)
          • OnLineStatusChanged(LocalizedLine)
          • ReadyForNextLine()
          • RunLine(LocalizedLine,Action)
          • RunOptions(DialogueOption[],Action<int>)
        • Effects
          • FadeAlpha(CanvasGroup,float,float,float,Action,InterruptionFlag)
          • Typewriter(TextMeshProUGUI,float,Action,Action,InterruptionFlag)
        • FindVoiceOver
          • GetAsseetsInMatchingLanguageDirectory(string[],string)
          • GetMatchingVoiceOverAudioClip(string,string)
          • SearchAssetDatabase(string,string)
        • InMemoryVariableStorage
          • showDebug
          • TypeMappings
          • Clear()
          • Contains(string)
          • DeserializeAllVariablesFromJSON(string)
          • GetDebugList()
          • LoadFromFile(string)
          • LoadFromPlayerPrefs()
          • LoadFromPlayerPrefs(string)
          • SaveToFile(string)
          • SaveToPlayerPrefs()
          • SaveToPlayerPrefs(string)
          • SerializeAllVariablesToJSON(bool)
          • SetValue(string,bool)
          • SetValue(string,float)
          • SetValue(string,string)
          • TryGetValue(string,T)
        • InterruptionFlag
          • Clear()
          • Set()
          • Interrupted
        • LanguageAttribute
        • LineProviderBehaviour
          • textLanguageCode
          • GetLocalizedLine(Yarn.Line)
          • PrepareForLines(IEnumerable<string>)
          • Start()
          • LinesAvailable
          • YarnProject
        • LineView
          • DismissLine(Action)
          • OnContinueClicked()
          • OnLineStatusChanged(LocalizedLine)
          • Reset()
          • RunLine(LocalizedLine,Action)
          • Start()
          • Update()
        • Localization
          • AddLocalizedObject(string,T)
          • AddLocalizedObjects(IEnumerable<KeyValuePair<string, T>>)
          • AddLocalizedString(string,string)
          • AddLocalizedStrings(IEnumerable<KeyValuePair<string, string>>)
          • AddLocalizedStrings(IEnumerable<StringTableEntry>)
          • Clear()
          • ContainsLocalizedObject(string)
          • ContainsLocalizedString(string)
          • GetLineIDs()
          • GetLocalizedObject(string)
          • GetLocalizedString(string)
          • SetLocalizedObject(string,T)
          • ContainsLocalizedAssets
          • LocaleCode
          • UsesAddressableAssets
        • LocalizedLine
          • RawText
          • Status
          • Substitutions
          • TextID
          • CharacterName
          • Text
          • TextWithoutCharacterName
        • OptionsListView
          • Reset()
          • RunLine(LocalizedLine,Action)
          • RunOptions(DialogueOption[],Action<int>)
          • Start()
        • OptionView
          • OnOptionSelected
          • InvokeOptionSelected()
          • OnPointerClick(PointerEventData)
          • OnPointerEnter(PointerEventData)
          • OnSubmit(BaseEventData)
          • Option
        • SampleRenderDetector
        • SerializedDictionary
          • Add(TKey,TValue)
          • Add(KeyValuePair<TKey, TValue>)
          • Clear()
          • Contains(KeyValuePair<TKey, TValue>)
          • ContainsKey(TKey)
          • CopyTo(KeyValuePair<TKey, TValue>[],int)
          • GetEnumerator()
          • Remove(TKey)
          • Remove(KeyValuePair<TKey, TValue>)
          • TryGetValue(TKey,TValue)
          • Count
          • IsReadOnly
          • this[TKey key]
          • Keys
          • Values
        • StringTableEntry
          • Comment
          • File
          • ID
          • Language
          • LineNumber
          • Lock
          • Node
          • Text
          • StringTableEntry(StringTableEntry)
          • CreateCSV(IEnumerable<StringTableEntry>)
          • Equals(object)
          • GetHashCode()
          • ParseFromCSV(string)
          • ToString()
        • TextLineProvider
          • GetLocalizedLine(Yarn.Line)
          • PrepareForLines(IEnumerable<string>)
          • LinesAvailable
        • VariableStorageBehaviour
          • Clear()
          • Contains(string)
          • SetValue(string,bool)
          • SetValue(string,float)
          • SetValue(string,string)
          • TryGetValue(string,T)
        • VoiceOverPlaybackUnity
          • fadeOutTimeOnLineFinish
          • waitTimeAfterLineComplete
          • waitTimeBeforeLineStart
          • OnLineStatusChanged(LocalizedLine)
          • RunLine(LocalizedLine,Action)
        • YarnActionAttribute
          • Name
        • YarnCommandAttribute
          • CommandString
          • Injector
        • YarnFunctionAttribute
          • FunctionName
        • YarnLinesAsCanvasText
          • stringsToViews
          • yarnProject
          • OnTextLanguagePreferenceChanged()
          • StringObjectDictionary
        • YarnParameterAttribute
          • Injector
        • YarnProject
          • baseLocalization
          • compiledYarnProgram
          • localizations
          • searchAssembliesForActions
          • GetLocalization(string)
          • GetProgram()
        • YarnStateInjectorAttribute
          • Injector
Powered by GitBook
LogoLogo

Community

  • Discord
  • Bluesky
  • Mastodon

Support Our Work

  • Itch
  • Unity Asset Store
  • Patreon

Yarn Spinner® and Secret Lab® are trade marks of Secret Lab Pty. Ltd., and are used by Yarn Spinner Pty. Ltd. under license.

On this page
  • Variables
  • Setting Variables
  • Variables and Types
  • Variables and Expressions
  • Using Variables in Lines
  • Variables and Storage

Was this helpful?

Edit on GitHub
Export as PDF
  1. Writing Your Dialogue
  2. Writing in Yarn

Variables

The Yarn language is a full programming language, which means it has support for writing code that let you control how the dialogue in your game works. In this section, you'll learn how to use variables to control your dialogue.

Variables

Variables store information. Variables can store one of three types of information: numbers, strings, and booleans.

Type
Possible Values
Examples

Number

Any whole or decimal number

1, 2.5, 3468900, -500

String

Any sequence of letters, numbers and other characters, enclosed in quotes.

"Hello", "✓", "A whole sentence."

Boolean

Either the value true or the value false.

true, false

Every variable has a name. In Yarn Spinner, all variable names start with a dollar sign ($).

Setting Variables

You put information into a variable by using the <<set>> command. For example, the following code puts a string, "Hello, Yarn!", into a variable called $greeting:

<<set $greeting to "Hello, Yarn!">>

As with node titles, variable names must not contain spaces. They must be made up of only letters, numbers and underscores, and the first character must be a letter.

Variables and Types

Each variable can only store one type of value. Variables can change their value at any time, but they can never change their type.

For example, the following code will work:

// Set some initial values in some variables
<<set $myCoolNumber to 7>>
<<set $myFantasticString to "wow, text!">>

// Now change them!
<<set $myCoolNumber to 8>>
<<set $myFantasticString to "incredible!">>

This works because while the value of each of the variable changes, the type doesn't. However, the following code will not work:

// Set some initial values in some variables
<<set $myCoolNumber to 7>>
<<set $myFantasticString to "wow, text!">>

// This will NOT work, because you can't change types!
<<set $myCoolNumber to "8">>
<<set $myFantasticString to 42>>

Starting with Yarn Spinner 2.0, variables are never null. All variables are required to have a value.

<<set $variableName to "a string value">>

Variables and Expressions

You can work with the values inside variables. For example, numbers can be multiplied, strings can be added together, and boolean values can have logical operations (like and and or) applied to them. When values are used together like this, it's called an expression.

<<set $numberOfSidesInATriangle = 2 + 1>>

<<set $numberOfSidesInASquare = $numberOfSidesInATriangle + 1>>

An expression needs to be a single type. You can't work with values of different types in a single expression. For example, the following code will not work:

// This will NOT work, because you can't add a string and a number:
<<set $broken = "hello" + 1>>

Yarn Spinner provides built-in functions for converting between certain types:

  • The string function converts values of any type into a string.

  • The number function converts values of any type into a number (if it can be interpreted as one.)

  • The bool function converts values of any type into a boolean value (if it can be interpreted as one.)

Using Variables in Lines

To show the contents of a variable, you put it inside braces ({ }) inside a line. The value of that variable will appear in its place.

For example:

<<set $variableName to "a string value">>
The value of variableName is {$variableName}.
The value of variableName is a string value.

Variables and Storage

Yarn Spinner doesn’t manage the storage of information in variables itself. Instead, your game provides a variable storage object to Yarn Spinner before you start running dialogue.

When Yarn Spinner needs to know the value of a variable, it will ask the variable storage object you’ve given it. When Yarn Spinner wants to set the value of a variable, it will provide the value and the name of the variable. In this way, your game has control over how data is stored.

PreviousNodes, Lines, and OptionsNextFlow Control

Last updated 3 years ago

Was this helpful?

The specifics of how variables need to be stored will vary depending on what game engine you're using Yarn Spinner in. To learn more about variable storage in Unity, see .

✍️
Variable Storage