MonoBehaviour Singletons in Unity

There are a lot of tutorials on singletons and what they are, so I’m gonna skip that.

I wrote a class that’s a template for making Unity MonoBehavior Singletons that can run with an update and stuff, and which don’t suffer from the usual “null” pointer tedium.

I’m not going to do too much explaining of it here, as it’s sort of self-explanatory, I think. Basically, the “self” accessor always makes sure you have a gameObject with the script running on it, and provides a reference. So when you use Class.self in another script, you never have to worry about it being null.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class SingletonTemplate : MonoBehaviour
  private static SingletonTemplate _self = null;
  public static SingletonTemplate self
      if(_self == null)
      return _self;
  private static void InitSingleton()
    _self = new GameObject("SingletonTemplate").AddComponent<SingletonTemplate>();  

If you want to use this, just find-replace “SingletonTemplate” with your class name, and you’ve got a template for making it into a monobehaviour singleton.

Bookmark the permalink.

Comments are closed.