Skip to content

Instantly share code, notes, and snippets.

@luke161
Last active June 20, 2024 15:20
Show Gist options
  • Save luke161/5ec0d91f4bf2366dfafb3014c6bd9466 to your computer and use it in GitHub Desktop.
Save luke161/5ec0d91f4bf2366dfafb3014c6bd9466 to your computer and use it in GitHub Desktop.
Unity MonoBehaviour Singleton. Base class for creating a singleton in Unity, handles searching for an existing instance, useful if you've created the instance inside a scene. Also handles cleaning up of multiple singleton instances in Awake.
/**
* Singleton.cs
* Author: Luke Holland (http://lukeholland.me/)
*/
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static readonly object _instanceLock = new object();
private static bool _quitting = false;
public static T instance {
get {
lock(_instanceLock){
if(_instance==null && !_quitting){
_instance = GameObject.FindObjectOfType<T>();
if(_instance==null){
GameObject go = new GameObject(typeof(T).ToString());
_instance = go.AddComponent<T>();
DontDestroyOnLoad(_instance.gameObject);
}
}
return _instance;
}
}
}
protected virtual void Awake()
{
if(_instance==null) _instance = gameObject.GetComponent<T>();
else if(_instance.GetInstanceID()!=GetInstanceID()){
Destroy(gameObject);
throw new System.Exception(string.Format("Instance of {0} already exists, removing {1}",GetType().FullName,ToString()));
}
}
protected virtual void OnApplicationQuit()
{
_quitting = true;
}
}
@dyguests
Copy link

Perfect!
I used it to replace the old solution I had been using for several years

@sirbaconjr
Copy link

I loved the approach! Great work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment