Skip to content

Instantly share code, notes, and snippets.

@wcoastsands
Last active April 17, 2018 21:45
Show Gist options
  • Save wcoastsands/9d48c04dce73d7fe264d71ee00f32a50 to your computer and use it in GitHub Desktop.
Save wcoastsands/9d48c04dce73d7fe264d71ee00f32a50 to your computer and use it in GitHub Desktop.
A generic singleton class for use in creating single-instance managers in Unity.
using UnityEngine;
namespace Nikkolai
{
public abstract class SingletonBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
public static T instance { get { return GetInstance(); } }
[SerializeField, Tooltip("Determines whether the GameObject should be destroyed on scene loads.")]
protected bool m_DestroyOnLoad;
static T s_Instance;
static object s_Lock = new object();
static bool s_IsApplicationQuitting = false;
static T GetInstance ()
{
if (s_IsApplicationQuitting) return null;
// Outside of the new Unity job system, Unity executes all scripts on the main thread. As a precaution,
// GetInstance() includes the following lock statement in case it ever gets called from multiple threads.
lock (s_Lock)
{
if (s_Instance == null)
{
s_Instance = FindObjectOfType<T>();
if (s_Instance == null)
{
var gO = new GameObject(typeof(T).Name);
s_Instance = gO.AddComponent<T>();
}
}
return s_Instance;
}
}
protected virtual void Awake ()
{
if (instance != this) Destroy(gameObject);
if (!m_DestroyOnLoad) DontDestroyOnLoad(gameObject);
}
protected virtual void OnApplicationQuit ()
{
s_IsApplicationQuitting = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment