Eryk Dwornicki - Blog

Hello! My name is Eryk, and this is my home page! You can also find me here:

< Return to home

Unity: Fast Singleton GameManager that works always

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:

  1. Initialization order - the game manager is not created as the first-ever object, it is created on the first access
  2. Not-deterministic initialization — you don’t know at what moment the instance is created
  3. Non-linear access — first access of singleton is expensive as it needs to initialize the game object, you want it to be deterministic
  4. It’s slower —in singleton getter, you must always check the condition if the game instance is null

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: