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
  • Built-In Functions
  • visited(string node_name)
  • visited_count(string node_name)
  • random()
  • random_range(number a, number b)
  • dice(number sides)
  • round(number n)
  • round_places(number n, number places)
  • floor(number n)
  • ceil(number n)
  • inc(number n)
  • dec(number n)
  • decimal(number n)
  • int(number n)
  • Custom Functions

Was this helpful?

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

Functions

PreviousCommandsNextTags and Metadata

Last updated 1 year ago

Was this helpful?

A function is a block of code that provides a value to your Yarn scripts, which you can use in , or store in .

In Yarn Spinner scripts, functions perform two main kinds of task:

  • Functions let you get values that change over time, or that depend on other values. For example, the random function returns a different random number every time you call it.

  • Functions let you get data from your game back into your scripts.

You call a function inside an expression. For example:

// Inside an if statement:
<<if dice(6) == 6>>
    You rolled a six!
<<endif>>

// Inside a line:
Gambler: My lucky number is {random_range(1,10)}!

Built-In Functions

Yarn Spinner comes with several built-in functions for you to use.

visited(string node_name)

visted returns a boolean value of true if the node with the title of node_name has been entered and exited at least once before, otherwise returns false. Will return false if node_name doesn't match a node in project.

visited_count(string node_name)

visted_count returns a number value of the number of times the node with the title of node_name has been entered and exited, otherwise returns 0. Will return 0 if node_name doesn't match a node in project.

random()

random returns a random number between 0 and 1 each time you call it.

random_range(number a, number b)

random_range returns a random integer between a and b, inclusive.

dice(number sides)

dice returns a random integer between 1 and sides, inclusive.

For example, dice(6) returns a number between 1 and 6, just like rolling a six-sided die.

round(number n)

round rounds n to the nearest integer.

round_places(number n, number places)

round_places rounds n to the nearest number with places decimal points.

floor(number n)

floor rounds n down to the nearest integer, towards negative infinity.

ceil(number n)

ceil rounds n up to the nearest integer, towards positive infinity.

inc(number n)

inc rounds n up to the nearest integer. If n is already an integer, inc returns n+1.

dec(number n)

inc rounds n down to the nearest integer. If n is already an integer, inc returns n-1.

decimal(number n)

decimal returns the decimal portion of n. This will always be a number between 0 and 1. For example, decimal(4.51) will return 0.51.

int(number n)

int rounds n down to the nearest integer, towards zero.

This is different to floor, because floor rounds to negative infinity.

Custom Functions

You can define your own custom functions in Yarn Spinner. For more information, see .

Functions are not intended to be a way for you to send instructions to your game. For that purpose, you should use .

In particular, functions are not guaranteed to be called in the same order as they appear in your code, or even be called at all if Yarn Spinner believes the result can be cached. As much as possible, custom functions should be , and have no side effects besides returning a value based on parameters.

✍️
if statements
variables
# Defining Commands and Functions
commands
pure functions