Unity Singleton GameObject

I’ve seen a few singleton patterns flying around for Unity GameObjects, and thought I’d contribute my own. It will destroy duplicates of the MonoBehaviour, so you can create instances in code and┬áhave a GameObject in every scene with your singleton script attached and it won’t matter.

using UnityEngine;
 
namespace UnityHelper
{
    public abstract class SingletonMonoBehaviour<T> : MonoBehaviour
        where T : SingletonMonoBehaviour<T>
    {
        private static GameObject msSingleton = null;
 
		//
		public static string SingletonName
		{
			get
			{
				return typeof(T).ToString() + "?Singleton";
			}
		}
 
        //
        public static T Instance
        {
            get
            {
				T retVal = null;
 
				// If the singleton pointer is null
				if (msSingleton == null)
				{
					// See if the GameObject already exists
					msSingleton = GameObject.Find(SingletonName);
 
					// If it doesn't then create it
					if (msSingleton == null)
					{
						msSingleton = new GameObject();
					}
				}
 
				// With the GameObject, get our singleton monobehaviour
				retVal = msSingleton.GetComponent<T>();
 
				// If it doesn't exist yet, create it
				if (retVal == null)
				{
					retVal = msSingleton.AddComponent<T>();
				}
 
				return retVal;
            }
        }
 
        //
        private void Awake()
        {
			// If the singleton pointer isn't set yet, set it from this object
			if(msSingleton == null)
			{
				msSingleton = this.gameObject;
			}
 
			// If this monobehaviour is assigned to another GameObject, remove that GameObject
			if(msSingleton != this.gameObject)
			{	
				DestroyObject(this.gameObject);
			}
 
			// Otherwise, initialise this monobehaviour, this is our singleton instance
			else
			{
				msSingleton.name = SingletonName;
				msSingleton.hideFlags = HideFlags.DontUnloadUnusedAsset;
				DontDestroyOnLoad(msSingleton);
 
				OnSingletonCreated();
 
				if (Debug.isDebugBuild)
				{
					Debug.Log("Singleton Created : " + SingletonName);
				}
			}
        }
 
        //
        private void OnDestroy()
        {
			// If this is our singleton instance, then we do want to terminate our singleton
			if(msSingleton == this.gameObject)
			{
				msSingleton = null;
 
				OnSingletonDestroyed();
 
				if (Debug.isDebugBuild)
				{
					Debug.Log("Singleton Destroyed : " + SingletonName);
				}
			}
 
			// Otherwise it is just a duplicate instance
			else
			{
				if (Debug.isDebugBuild)
				{
					Debug.Log("Duplicate Singleton Destroyed " + SingletonName);
				}
			}
        }
 
		// These should be used instead of OnAwake() and OnDestroy() to prevent
		// duplicate instances setting up
		protected abstract void OnSingletonCreated();
		protected abstract void OnSingletonDestroyed();
    }
}

Since OnAwake() and OnDestroy() will get called as well for the duplicates, I’ve added two new methods OnSingletonCreated() and OnSingletonDestroyed() that should be used instead.

Now to implement, just make the monobehaviour you wish to be a singleton inherit off the generic.

namespace MySingletonProject
{
    public sealed class DispatcherMonoBehaviour : UnityHelper.SingletonMonoBehaviour<DispatcherMonoBehaviour>
    {
		//
		protected override void OnSingletonCreated()
		{
			// What you would normally do onAwake
		}
 
		//
		protected override void OnSingletonDestroyed()
		{
			// What you would normally do onDestroy
		}
 
        //
        void Update()
        {
		// do something
        }
    }
}

This code will allow you to destroy the GameObject through normal means as well if you want to be rid of the singleton until it is needed again.