(Unity) HowTo : Global Variables

“Global Variables” are special variables that are visible to many different parts of your program. Whereas a variable in a uScript graph (the little circles) can only be used within that graph, a “Global” variable can be used from Yarn Dialogue, uScript graphs, and even CSharp code. Global variables can be extremely useful for storing game-wide information, such as the player’s HP, information obtained from the player through dialogue (their favorite color maybe), the player’s relationship score with an NPC, the value of a timer as the clock ticks down (maybe a uScript graph could cause a timer variable to decrease, and yarn dialogue checks it to make NPCs more panicky if it is below a certain value). Etc etc etc.

The following tutorial shows you how to manipulate and use Global variables.

Preparation

In order for the following tutorial to work, you must…

  • Download and import this unitypackage into your project (be sure to use a 2020 version of unity).
  • Ensure your scenes have a DialogueRunner gameobject in your scene.
  • Make sure that your DialogueRunner gameobject has an “In Memory Variable Storage” component, and that this component is dragged into the DialogueRunner component’s “Variable Storage” property, like in the following gif–

Note that, once you download and import this package, your DialogueRunner gameobject will survive scene transitions. This means that you will want to load all of your Yarn files into the DialogueRunner gameobject that runs first (as this one will destroy any others in scenes you enter). Go to your first scene and load all of your Yarn scripts into the DialogueRunner you have there. You may need to rename nodes to make them distinct if multiple yarn files re-use node names.

Global Variables in uScript

four new uScript nodes are available for “setting” and for “getting” numbers and strings, allowing you to change and obtain the value of a global variable.

Search your uScript toolbox for “global” to find these four nodes.

Global Variables in Yarn

To manipulate or check global variables in your Yarn dialogue scripts, use them as described in the Yarn Dialogue Commands Tutorial.

Global Variables in CSharp

Setting

Numeric or string variables may be stored via the following function call from anywhere in your codebase.

GlobalVariables.Set();

Here’s an example–

Fun fact– under the hood, the new “” uScript nodes use this function call as well as the GlobalVariables.Get() functions below.

Getting

Numeric or string variables may be retrieved via the following two function calls from anywhere in your codebase.

GlobalVariables.GetString(); GlobalVariables.GetNumeric();

Updated: