LogoLogo
HomepageDiscordItchPatreon
Yarn Spinner 2.2
Yarn Spinner 2.2
  • ⭐Start Here
  • Writing Your Dialogue
    • ⌨️Editing with VS Code
      • Installing the Extension
      • Writing Yarn in VS Code
      • Previewing Your Dialogue
    • ✍️Writing in Yarn
      • Nodes, Lines, and Options
      • Variables
      • Flow Control
      • Markup
      • Commands
      • Functions
      • Tags and Metadata
    • 🪄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
        • Creating Custom Dialogue Views
        • Dialogue Advance Input
      • Variable Storage
        • In-Memory Variable Storage
        • Custom Variable Storage Components
      • Line Provider
        • Text Line Provider
        • Audio Line Provider
    • 🤖Commands and Functions
    • 🗺️Localizations and Assets
      • In-built Localisation
    • 💡Frequently Asked Questions / "How Do I...?"
  • 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
    • How to credit Yarn Spinner
  • 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)
          • GenerateUniqueVisitedVariableForNode(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
        • BasicBlock
          • AddDestination(string,Condition)
          • AddDestination(BasicBlock,Condition)
          • Ancestors
          • Descendants
          • DescendantsWithPlayerVisibleContent
          • Destinations
          • FirstInstructionIndex
          • Instructions
          • LabelName
          • Name
          • NodeName
          • PlayerVisibleContent
          • CommandElement
            • CommandText
          • Condition
            • DirectJump
            • ExpressionIsFalse
            • ExpressionIsTrue
            • Fallthrough
            • Option
          • Destination
            • Block
            • Condition
            • NodeName
            • Type
            • DestinationType
              • Block
              • Node
          • LineElement
            • LineID
          • OptionsElement
            • Options
            • Option
              • Destination
              • LineID
          • PlayerVisibleContentElement
        • CompilationJob
          • CompilationType
          • Files
          • Library
          • VariableDeclarations
          • CreateFromFiles(IEnumerable<string>,Library)
          • CreateFromFiles(string[])
          • CreateFromString(string,string,Library)
          • File
            • FileName
            • Source
          • Type
            • DeclarationsOnly
            • FullCompilation
            • StringsOnly
        • CompilationResult
          • ContainsImplicitStringTags
          • DebugInfo
          • Declarations
          • Diagnostics
          • FileTags
          • Program
          • StringTable
        • Compiler
          • Compile(CompilationJob)
          • FlattenParseTree(IParseTree)
          • GetDocumentComments(CommonTokenStream,ParserRuleContext,bool)
          • GetLineIDForNodeName(string)
        • DebugInfo
          • GetLineInfo(int)
          • LineInfo
            • CharacterNumber
            • FileName
            • LineNumber
            • NodeName
        • Declaration
          • ExternalDeclaration
          • CreateVariable(string,Yarn.IType,IConvertible,string)
          • Equals(object)
          • GetHashCode()
          • ToString()
          • DefaultValue
          • Description
          • IsImplicit
          • Name
          • Range
          • SourceFileLine
          • SourceFileName
          • SourceNodeName
          • Type
        • DeclarationBuilder
          • WithDefaultValue(System.IConvertible)
          • WithDescription(string)
          • WithImplicit(bool)
          • WithName(string)
          • WithRange(Yarn.Compiler.Range)
          • WithSourceFileName(string)
          • WithSourceNodeName(string)
          • WithType(IType)
          • Declaration
        • DeferredTypeDiagnostic
          • CreateDeferredTypeDiagnostic(string,Diagnostic)
          • diagnostic
          • Name
        • Diagnostic
          • Diagnostic(string,ParserRuleContext,string,DiagnosticSeverity)
          • Diagnostic(string,string,DiagnosticSeverity)
          • Diagnostic(string,DiagnosticSeverity)
          • Diagnostic(string,Range,string,DiagnosticSeverity)
          • Equals(object)
          • GetHashCode()
          • ToString()
          • Column
          • Context
          • FileName
          • Line
          • Message
          • Range
          • Severity
          • DiagnosticSeverity
            • Error
            • Info
            • Warning
        • FileParseResult
          • FileParseResult(string,IParseTree,CommonTokenStream)
          • Equals(object)
          • GetHashCode()
          • Name
          • Tokens
          • Tree
        • FunctionTypeBuilder
          • WithParameter(IType)
          • WithReturnType(IType)
          • FunctionType
        • IndentAwareLexer
          • IndentAwareLexer(ICharStream,TextWriter,TextWriter)
          • NextToken()
          • Warnings
          • Warning
            • Message
            • Token
        • InstructionCollectionExtensions
          • GetBasicBlocks(Node)
        • Position
          • Equals(object)
          • GetHashCode()
          • Character
          • Line
        • Range
          • Range()
          • Range(int,int,int,int)
          • Equals(object)
          • GetHashCode()
          • End
          • Start
        • StringInfo
          • fileName
          • isImplicitTag
          • lineNumber
          • metadata
          • nodeName
          • text
          • ToString()
        • Utility
          • AddTagsToLines(string,ICollection<string>)
          • DetermineNodeConnections(string[])
          • ExtractStringBlocks(IEnumerable<Node>)
          • 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)
        • DialogueAdvanceInput
          • continueAction
          • continueActionKeyCode
          • continueActionReference
          • continueActionType
          • dialogueView
          • enableActionOnStart
          • Action
          • ContinueActionType
            • InputSystemAction
            • InputSystemActionFromAsset
            • KeyCode
            • None
        • DialogueCharacterNameView
          • onDialogueStarted
          • onNameNotPresent
          • onNameUpdate
          • DialogueStarted()
          • RunLine(LocalizedLine,Action)
        • DialogueOption
          • DialogueOptionID
          • IsAvailable
          • Line
          • TextID
        • DialogueReference
          • nodeName
          • project
          • DialogueReference()
          • DialogueReference(YarnProject,string)
          • IsValid
        • DialogueRunner
          • dialogueViews
          • lineProvider
          • onCommand
          • onDialogueComplete
          • onNodeComplete
          • onNodeStart
          • runSelectedOptionAsLine
          • startAutomatically
          • startNode
          • verboseLogging
          • yarnProject
          • AddCommandHandler(string,Delegate)
          • 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,Delegate)
          • 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)
          • LoadStateFromPlayerPrefs(string)
          • NodeExists(string)
          • OnViewRequestedInterrupt()
          • RemoveCommandHandler(string)
          • RemoveFunction(string)
          • ResetDialogue(string)
          • SaveStateToPlayerPrefs(string)
          • SetDialogueViews(DialogueViewBase[])
          • SetInitialVariables(bool)
          • SetProject(YarnProject)
          • SplitCommandText(string)
          • StartDialogue(string)
          • Stop()
          • CurrentNodeName
          • Dialogue
          • IsDialogueRunning
          • VariableStorage
          • StringUnityEvent
        • DialogueViewBase
          • requestInterrupt
          • DialogueComplete()
          • DialogueStarted()
          • DismissLine(Action)
          • InterruptLine(LocalizedLine,Action)
          • RunLine(LocalizedLine,Action)
          • RunOptions(DialogueOption[],Action<int>)
          • UserRequestedViewAdvancement()
        • Effects
          • FadeAlpha(CanvasGroup,float,float,float,CoroutineInterruptToken)
          • Typewriter(TextMeshProUGUI,float,Action,CoroutineInterruptToken)
          • CoroutineInterruptToken
            • Complete()
            • Interrupt()
            • Start()
            • CanInterrupt
            • WasInterrupted
        • InMemoryVariableStorage
          • showDebug
          • Clear()
          • Contains(string)
          • GetAllVariables()
          • GetDebugList()
          • SetAllVariables(Dictionary<string, float>,Dictionary<string, string>,Dictionary<string, bool>,bool)
          • SetValue(string,bool)
          • SetValue(string,float)
          • SetValue(string,string)
          • TryGetValue(string,T)
        • LanguageAttribute
        • LineMetadata
          • GetLineIDs()
          • GetMetadata(string)
        • LineProviderBehaviour
          • textLanguageCode
          • GetLocalizedLine(Yarn.Line)
          • PrepareForLines(IEnumerable<string>)
          • Start()
          • LinesAvailable
          • YarnProject
        • LineView
          • DismissLine(Action)
          • InterruptLine(LocalizedLine,Action)
          • OnContinueClicked()
          • RunLine(LocalizedLine,Action)
          • UserRequestedViewAdvancement()
        • 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
          • Metadata
          • RawText
          • 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)
          • GetAllVariables()
          • SetAllVariables(System.Collections.Generic.Dictionary<string,float>,System.Collections.Generic.Dicti
          • SetValue(string,bool)
          • SetValue(string,float)
          • SetValue(string,string)
          • TryGetValue(string,T)
        • VoiceOverView
          • audioSource
          • fadeOutTimeOnLineFinish
          • waitTimeAfterLineComplete
          • waitTimeBeforeLineStart
          • DismissLine(Action)
          • InterruptLine(LocalizedLine,Action)
          • RunLine(LocalizedLine,Action)
          • UserRequestedViewAdvancement()
        • YarnActionAttribute
          • Name
        • YarnCommandAttribute
          • CommandString
          • Injector
        • YarnFunctionAttribute
          • FunctionName
        • YarnLinesAsCanvasText
          • stringsToViews
          • yarnProject
          • OnTextLanguagePreferenceChanged()
          • StringObjectDictionary
        • YarnParameterAttribute
          • Injector
        • YarnProject
          • baseLocalization
          • compiledYarnProgram
          • lineMetadata
          • localizations
          • searchAssembliesForActions
          • GetLocalization(string)
          • GetProgram()
          • Program
        • YarnStateInjectorAttribute
          • Injector
Powered by GitBook

Community

  • Discord
  • Bluesky
  • Mastodon
  • Itch

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
  • Text
  • How do I style text? How do I make some words bold, italic, colorful, etc?
  • How do I animate wavy text, like in Night In The Woods?
  • How do I use Yarn Markup?
  • Variables
  • How do I print the value of a variable in dialogue?
  • How do I read / write Yarn variables from a C# script?
  • How do I read / write C# variables from a Yarn script?
  • How do I 'sync' variables between Yarn and C#?
  • How do I load and save data / variables / dialogue state? (Like for a save game system)
  • Control flow
  • How do I jump to a specific node? How do I switch nodes while dialogue is running?
  • How do I jump to a specific line in a node?
  • Interaction / UI
  • How do I continue dialogue with key/button press instead of clicking the continue button?
  • How do I show the last line of text when options are shown? How do I skip the last line of text before a set of options?
  • How do I show the character name / portrait? How do I customize dialogue display?
  • How do I play a Yarn node when I click / tap on an object?
  • How do I play a Yarn node when I approach an object and press a button? (RPG-like talking to NPCs)
  • How do I position a speech bubble above an NPC's head, like in A Short Hike?
  • How do I implement a resizing dialogue bubble / SMS messaging interface?
  • System
  • How do I generate a Yarn Project at runtime? How do I load/compile Yarn scripts at runtime?
  • How many Yarn files should I have? Can my entire game be in one project or script? Or one project per scene? Is my project or file too big?

Was this helpful?

Edit on GitHub
Export as PDF
  1. Working With Unity

Frequently Asked Questions / "How Do I...?"

Common questions and solutions for using Yarn Spinner in Unity.

PreviousIn-built LocalisationNextChoose-Your-Path Game

Last updated 1 year ago

Was this helpful?

Text

How do I style text? How do I make some words bold, italic, colorful, etc?

Yarn Spinner doesn't do text rendering, you have to use existing Unity systems like TextMeshPro. Fortunately, TMP supports HTML-like rich text tags. See the .

Alice: This text is <b>bold!</b>
Bob: This text is <color=red>red!</color>

// NOTE: '#' is a special character in Yarn, used for line tags.
// To use a HTML color hex code, you must "escape" the "#" character with a "\"
Carol: Wow I'm <color=\#ff00ff>purple</color>!

However, this bespoke approach is impractical for longer scripts or bigger projects. We recommend using TextMeshPro's Style Sheets, which make it much easier to write consistently styled text. See the .

How do I animate wavy text, like in Night In The Woods?

Yarn Spinner doesn't handle text rendering. You'll need a separate wavy text system, like .

How do I use Yarn Markup?

Markup lets you mark a range of text (words, phrases) in a generic way, for whatever use. You could use it to style text, add sentence markers, make clickable words, etc.

// Yarn script example of custom "wavy text" markup.
Oh, [wave]hello[/wave] there!

// After compiling, text will look like: "Oh, hello there!"
// And then the resulting markup data will look like:
// - name: "wave"
// - position: 4
// - length: 5

Variables

How do I print the value of a variable in dialogue?

<<set $variableName to "a string value">>
The value of variableName is {$variableName}.
// This will appear as "The value of variableName is a string value."

How do I read / write Yarn variables from a C# script?

Don't forget the $ when writing the variable's name!

variableStorage = GameObject.FindObjectOfType<InMemoryVariableStorage>();
float testVariable;
variableStorage.TryGetValue("$testVariable", out testVariable);
variableStorage.SetValue("$testVariable", testVariable + 1);

How do I read / write C# variables from a Yarn script?

static int myNumber = 10;

// note: all Yarn Functions must be static
[YarnFunction("getMyNumber")]
public static int GetMyNumber() { 
    return myNumber; 
}

// Yarb Commands can be static or non-static
[YarnCommand("setMyNumber")]
public static void SetMyNumber(int newNumber) { 
    myNumber = newNumber;
}

Then call the functions and commands in Yarn:

My number is { getMyNumber() }!
<<setMyNumber 999>>
But now it's { getMyNumber() }!

How do I 'sync' variables between Yarn and C#?

How do I load and save data / variables / dialogue state? (Like for a save game system)

It is not currently possible to save or restore the specific line that the dialogue is running.

Control flow

How do I jump to a specific node? How do I switch nodes while dialogue is running?

How do I jump to a specific line in a node?

Interaction / UI

How do I continue dialogue with key/button press instead of clicking the continue button?

How do I show the last line of text when options are shown? How do I skip the last line of text before a set of options?

How do I show the character name / portrait? How do I customize dialogue display?

How do I play a Yarn node when I click / tap on an object?

Write input code to detect clicking / tapping, then call DialogueRunner.StartDialogue().

How do I play a Yarn node when I approach an object and press a button? (RPG-like talking to NPCs)

This implementation will vary for every game, so we purposely do not attempt to design a one-size-fits-all generic NPC system. Here's some example pseudo-code to make your own:

if (player presses SPACE)
    then find the nearest NPC
    get that NPC's dialogue node name
    call DialogueRunner.StartDialogue() with the NPC's dialogue node
    disable player movement

How do I position a speech bubble above an NPC's head, like in A Short Hike?

The math / code is a little complicated. Calculate the NPC's on-screen position, then convert this screen position to UI canvas space, and reposition the dialogue bubble.

How do I implement a resizing dialogue bubble / SMS messaging interface?

This is more about Unity UI rather than Yarn Spinner. For a working example, see the "Phone Chat" sample. (In Unity, go to Window > Package Manager, and select Yarn Spinner package. Expand the "Samples" dropdown and select "Phone Chat" and import it.)

System

How do I generate a Yarn Project at runtime? How do I load/compile Yarn scripts at runtime?

How many Yarn files should I have? Can my entire game be in one project or script? Or one project per scene? Is my project or file too big?

There is no real technical limit on the number of Yarn scripts or the size of Yarn Projects. You decide how to organize your data, and every project has different needs. Some factors to consider:

  • Simplicity. Putting everything into one big script file or one big project file is simpler sometimes.

  • Ease of writing. Writers may prefer to think in terms of one file per scene, one file per chapter.

Note that YS only processes the text data. You must still code the actual markup effect yourself. See .

Wrap the variable (or any expression) in curly braces ({, }) to evaluate and output it. For more info, see .

To read Yarn variables from C#, use . To write Yarn variables from C#, use .

To read and write C# variables from Yarn, you must first code in C#.

See the previous answers on working with variables. But we recommend avoiding any "sync" pattern, because then you'll have to track and maintain the same data in two different places. Programmers usually prefer a . Data should live in only one place. Variables should either live in Yarn or live in C#, and not in both.

To save the current node, save the value of somewhere, e.g. to Unity's . Then to restore it, call and pass in the saved node name.

To save variables, see . Then to load variables, call . These methods use Unity's built-in JSON utility to serialize a dictionary of variables to Unity's .

For custom save systems, create your own by subclassing VariableStorageBehaviour and implementing its methods. Study as an example. For more info, see .

To jump to a node from Yarn, use <<jump (nodeName)>>. See .

To jump to a node with C#, just call , even if there's already dialogue running.

Jumping to a specific line in a node is currently not supported. Instead, .

In most cases, use the .

For more control, call on a Dialogue View, or on a Line View. See .

Yarn Spinner automatically adds a #lastline tag to a line when the next step is a set of options. Create a that uses to check for #lastline and perform the behavior you want.

To display anything in Yarn Spinner, use a component. for dialogue, for choices.

Most projects will need custom views. We recommend a modular architecture where each UI element has its own LineView component. For example, a nameplate bubble has a that displays , while the dialogue text window is another Line View that displays . See .

For a working example, see the "Visual Novel" sample. (In Unity, go to Window > Package Manager, and select Yarn Spinner package. Expand the "Samples" dropdown and select "Visual Novel" and import it.) Specifically, see which inherits from DialogueViewBase, and changes the character name window background color (among other effects) based on the character name.

The example tutorial can walk you through this step-by-step.

For a working example, see the "Space" sample. (In Unity, go to Window > Package Manager, and select Yarn Spinner package. Expand the "Samples" dropdown and select "Space" and import it.) Specifically, see for how to search for nearby NPCs from a list.

For a working example, see the "3D" sample. (In Unity, go to Window > Package Manager, and select Yarn Spinner package. Expand the "Samples" dropdown and select "3D" and import it.) Specfically, see which has a method WorldToAnchoredPosition() that does a lot of this UI positioning math.

To make a resizing dialogue bubble that automatically fits text, you will need a complex UI setup. Study the UI game objects and components in the sample scene. For more context about how it works, see .

The intended workflow is to generate and compile Yarn Projects at editor time, not runtime. See .

As of v2.x, Yarn Spinner Unity no longer supports runtime loading. Instead, Yarn Projects compile at editor time into bytecode. The source text and parser no longer ship with the game build. If you have specific runtime needs, you might be better off using Yarn Spinner Unity v1.x instead, or use a different Yarn implementation on a different platform -- see .

Localization. 1 Yarn Project = 1 CSV spreadsheet per language. When translating, it is usually easier to work with fewer files, rather than fragmenting the translation across many files. As a workaround for games that need multiple Yarn Projects, you may prefer to create a single editor-only Yarn Project that's just for generating string files and translations. See .

💡
TextMeshPro: Rich Text docs
TextMeshPro: Style Sheets docs
Text Animator
Markup
Variables
VariableStorageBehaviour.TryGetValue<T>()
VariableStorageBehaviour.SetValue()
Yarn Functions and Commands
"single source of truth"
DialogueRunner.CurrentNodeName
PlayerPrefs
DialogueRunner.StartDialogue()
DialogueRunner.SaveStateToPlayerPrefs()
DialogueRunner.LoadStateFromPlayerPrefs()
PlayerPrefs
variable storage
InMemoryVariableStorage.cs
Guide: Yarn Variables and Variable Storage
Nodes, Lines, and Options
DialogueRunner.StartDialogue()
Dialogue Advance Input
UserRequestedViewAdvancement()
OnContinuedClicked()
Creating Custom Dialogue Views
Custom Dialogue View
YarnProject.lineMetadata.GetMetadata()
Dialogue View
Line View
Options List View
Dialogue Character Name View
LocalizedLine.CharacterName
LocalizedLine.TextWithoutCharacterName
Creating Custom Dialogue Views
VNManager.cs
NPC Dialogue Game
PlayerCharacter.cs
YarnCharacterView.cs
this Unity UI Layout Groups explainer by Hallgrim Games
Yarn Projects
Community Projects
Localizations and Assets
jump to the start of a node