Eryk Dwornicki - BlogHello! My name is Eryk, and this is my home page! You can also find me here: |
A GameManager is a common concept in Unity games — it is a class that stores the “global” state of the game. Often it is implemented using the “Unity Singleton” pattern — meaning on first access you create a game object, initialize it, etc. That has many problems:
In this post, I want to share with you a way to create a “GameManager” singleton class that works always.
using UnityEngine; class GameManager : MonoBehaviour { public static GameManager instance; [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] private static Initialize() { if (instance == null) { instance = new GameObject(nameof(GameManager), typeof(GameManager)).GetComponent(); } } private void Awake() { Debug.Log("GameManager has been created!"); DontDestroyOnLoad(this); } }
After you do it that way you can safely in constant-time access the game manager from any place in your game code.
The idea can be expanded further: