Skip to content

"On Game Design"

Mike Stout – Video Game Designer

Menu
  • Game Design
  • Bloggage
  • Play By Blog
Menu

Unity: MonoBehaviour Singletons Template

Posted on March 30, 2015May 22, 2019 by Dodger

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
{
  //SINGLETON
  private static SingletonTemplate _self = null;
  
  public static SingletonTemplate self
  {
    get
    {
      if(_self == null)
        InitSingleton();
      
      return _self;
    }//get
  }//self
  
  private static void InitSingleton()
  {
    _self = new GameObject("SingletonTemplate").AddComponent<SingletonTemplate>();  
  }//InitSingleton
}//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.

Categories

  • Bloggage (15)
  • Game Design (34)
  • Play By Blog (48)
    • Dames, Dollars, and Derringers [Abandoned] (13)
    • Ward 32 [finished] (35)
  • Podcasts (2)
© 2023 "On Game Design" | Powered by Minimalist Blog WordPress Theme