Table of Contents
The GlobalVariable<T>
script allows you to create and manage global variables that can be used anywhere in your Unity project. The variables are stored as ScriptableObjects, and the script provides a mechanism to notify other parts of the code about changes in the variable's value through events. This pattern is useful for managing global states and events that affect the behavior of the game.
To get a local copy up and running follow these simple example steps.
- Download or fork this project
- Move the content to your Unity project (if preferred, only the Scripts folder is necessary)
Create a new script that inherits from GlobalVariable, where T is the type of the variable. Example:
- Create a global float variables script
GlobalFloatVariable.cs
using UnityEngine; [CreateAssetMenu(menuName = "Global Variables/Float Type", fileName = "GlobalFloatVariable")] public class GlobalFloatVariable : GlobalVariable<float> { }
- Create an instance of the global variable by right-clicking on the desired folder in the Project tab window and choosing the option (in this example)
Create > Global Variables > Global Float Variable
- Give your new global variable a name, for example,
PlayerHealth
- Now, to access it, simply reference the Scriptable Object created in your scripts. Example:
TestGlobalFloatVariable.cs
using System.Collections; using UnityEngine; public class TestGlobalFloatVariable : MonoBehaviour { [SerializeField] private GlobalFloatVariable _playerHealth; //The reference for the GlobalFloatVariable private IEnumerator Start() { //Subscribe to the player health's OnChange event to be notified when the value changes. _playerHealth.OnChange.AddListener(OnPlayerHealthChange); Debug.Log($"[TestGlobalFloatVariable] Player health value: {_playerHealth.Value}"); string timestamp = System.DateTime.Now.ToString("HH:mm:ss.fff"); Debug.Log($"[TestGlobalFloatVariable][{timestamp}] Change player health to 100 in 5 second."); //Wait and set the player health to 100. yield return new WaitForSeconds(5); _playerHealth.Value = 100; } private void OnPlayerHealthChange(float value) { string timestamp = System.DateTime.Now.ToString("HH:mm:ss.fff"); Debug.Log($"[TestGlobalFloatVariable][{timestamp}] Player health changed to {value}"); } }
LuizThiago - @CodeLuiz - [email protected]
Project Link: https://github.com/LuizThiago/GlobalVariables