Global Variables in Unity

by Michael Sacco Published August 21, 2023

Quick Start

Hey. I know you. You’re a new Unity game developer. You have a thing in your scene. You want one thing in your scene to get some info from another thing in your scene. And, you’re stuck.

Well, I have the article for you. Continue reading to learn how to use global variables in Unity.

Create a Global Variable

To make a global variable in Unity, you need to set it up. In this example, we create a singleton of GlobalVariables with a global variable, Player.

using UnityEngine;

public class GlobalVariables : MonoBehaviour
{
  // This is where you create the global variable that can be accessed from anywhere.
  
  public GameObject Player;
  
  // This part helps ensure there's only one instance of this class.
  private static GlobalVariables instance;
  public static GlobalVariables instance
  
  {
    get { return instance; }
  }
  private void Awake()
  {
    // Check if there's already an instance of this class. If yes, destroy this one. If not, set this as the instance.
    if (instance != null && instance != this)
    {
      Destroy(gameObject);
    }
    else
    {
      instance = this;
    }
  }
}

Set a Global Variable

Once you have your global variable set up, you can assign a value to it using code like this:

using UnityEngine;

public class PlayerComponent : MonoBehaviour
{
  void Start()
  {
    // Here, we're saying the global player variable is now equal to this object.
    GlobalVariables.Instance.Player = gameObject;
  }
}

Access a Global Variable

Now that you have set the global variable, you can use it from other parts of your code. In this example, we have an enemy. The enemy moves towards the Player global variable every frame.

using UnityEngine;

public class EnemyComponent : MonoBehaviour
{
  private void Update()
  {
    // This line makes the enemy move towards the player's position each frame.
    transform.position = Vector3.MoveTowards(
      transform.position,
      GlobalVariables.Instance.Player.transform.position,
      1f * Time.deltaTime
    );
    Debug.Log(GlobalVariables.Instance.Player);
  }
}

What you need to know about Global Variables in Unity

  • If you use many global variables, it will be more difficult to fix problems in your game. Any part of your game can affect a global variable. This makes it more challenging to identify the cause of an issue.
  • Do not over-use global variables.
  • Use global variables for important global information, such as the game state or important global options.
  • You should organize your code in smaller parts using events, delegates, and scriptable objects.

Understanding Global Variables in Unity

When you make a game, you need to make sure that the different parts of your game work together.

Global variables help make this happen. These variables are powerful because they empower your components to share key global information more easily.

In this explanation, we will talk about why global variables are important when making a game in Unity. We will see how they help different parts of the game talk to each other, keep the code organized, and make it quicker to build games.

The basic idea behind Global Variables

In this section, we will walk through the basic concepts of using global variables.

You need to take the following steps to use a global variable:

  1. Create a global variable
  2. Prevent multiple instances of your global variable
  3. Assign a value to the variable
  4. Use the shared variable
  5. Coordinate different parts of your game

1. Create a Global Variable:

When you want to share a piece of information across different parts of your game, you can use a “global variable.” Any piece of your game’s code can access and use this type of variable. You can think of it like a message board. Fortunately, any part of your game can read or write to the message board. Unfortunately, message boards are messy and full of garbage.

2. Prevent Duplicate Globals

To create a global variable, you need to follow a certain process. In the code you write, you establish some rules to make sure that there’s only one version of this global variable. You do not want multiple versions of a global variable. Which version will your code use? Who knows. Now your cat model is spawning rockets. This rule is referred to as a Singleton pattern.

3. Assign a Value

Now that you have set up your global variable, you need to assign a value to it. In your game, you might have different objects, like a player character. You can take the player object and say, “Hey, you are now the value inside that special global variable.” It’s like giving a unique name to a certain thing so you can find it easily later.

4. Use the Shared Information

Now that the global variable has a value (like the player object), other parts of your game can use this information. For instance, you might have enemies that need to know where the player is. Instead of making the enemies figure it out on their own, you can just tell them to look at the global variable. They’ll see the player’s location and know where to move.

5. Coordinate Different Parts

The beauty of using global variables is that they help different parts of your game “talk” to each other without having to know all the details. This coordination can help your project work together more easily. It can also help your project explode. The player object, enemies, and maybe other objects can all interact because they have a common way to share important information. But, your UI and save system also have access to that important information. You might not want them to.

Global variables are a simple way to share data globally in your game. They make it easy for objects to work together. They can make your game’s code more organized and efficient. Just be careful to avoid over-using them.

Advantages of Global Variables

Global Variables come with some clear benefits that make game development smoother and more organized:

  • Sharing Data between Scenes:
    Imagine your game has different levels or scenes. Global variables let you pass important information between these scenes. For example, you can easily carry over a player’s score from one level to another.
  • Efficient Game State Management:
    You need to keep track of your game state. Global variables help you manage this game state easily. You can monitor things like whether a level is completed or how much health the player has left.
  • Reducing Duplicate Code:
    Writing the same code again and again is a hassle. Global variables can help here too. You can use them to store common values or settings that multiple parts of your game need. This way, you write the code once and use it wherever needed.

Disadvantages of Global Variables

While global variables have advantages, using them too much can lead to problems:

  • Too many Global Variables:
    If you have too many global variables all over, your code can get confusing. It’s like having a lot of cooks in the kitchen - things can quickly become chaotic.
  • Spaghetti Code:
    Overusing global variables can lead to “spaghetti code.” Every piece of your code can access and change every other piece of your code. Components become entangled. Anytime you try to change something, you risk the entire system breaking. Your code has become tangled and messy. Just like a big, delicious bowl of spaghetti and meatballs.

Global Variable Design Patterns

  • Singletons:
    Use the Singleton design pattern to ensure that only one instance of your global variable exists in order to avoid multiple copies of global instances.
  • Static Variables:
    Use Static variables so that you don’t need a reference to a specific instance of a class - just the class type.
  • Editor Considerations:
    You can set global variables right in Unity’s editor. Or, you can write code to set them when your game starts. Either way is fine.
  • Debugging:
    Be super careful when different parts of the game try to change the same global variable at once. This can cause bugs that are hard to find.

Use Global Variables Carefully

Global variables can make it easier to develop interconnected, powerful systems in Unity. But, with great power comes great responsibility. Use global variables carefully and thoughtfully to build your game quickly and release it without game-breaking bugs.

Continue Learning

I’m sure you’d like to continue learning more about Global Variables. And, you’re probably interested in alternatives to global variables as well. I put together a list of further reading for you.

Free download: Indie Game Marketing Checklist

Download now

Category

design

Don't forget to share this post!

Popular assets for Unity

See all assets ->
    Cutting-edge volumetric fog and volumetric lighting with support for transparent materials.
    Volumetric clouds, day night cycles, dynamic skies, global lighting, weather effects, and planets and moons.
    A lightweight procedural skybox ideal for semi-stylized projects.
    Image-based Outlines for 2D and 3D games with variable line weight, color, and displacement options.
    Drag-and-drop ready-to-use ambient, impact, and spell particle effects.
    Per-pixel gaussian blur on your entire screen, part of the UI, or in-scene objects.

Free Indie Game Marketing Checklist

Learn how to make your game successful with this handy checklist.

Download for free