Skip to content

Instantly share code, notes, and snippets.

@Grave18
Forked from luke161/Singleton.cs
Last active July 28, 2022 13:31
Show Gist options
  • Save Grave18/c46019462f4365a9dc1f7f91e853e8ab to your computer and use it in GitHub Desktop.
Save Grave18/c46019462f4365a9dc1f7f91e853e8ab 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.
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static readonly object _instanceLock = new();
private static bool _quitting;
public static T Instance
{
get
{
lock (_instanceLock)
{
if (_instance is not null || _quitting)
{
return _instance;
}
_instance = FindObjectOfType<T>();
if (_instance is not null)
{
return _instance;
}
GameObject go = new(typeof(T).ToString());
_instance = go.AddComponent<T>();
DontDestroyOnLoad(_instance.gameObject);
return _instance;
}
}
}
protected virtual void Awake()
{
if (_instance is null)
{
_instance = gameObject.GetComponent<T>();
}
else if (_instance.GetInstanceID() != GetInstanceID())
{
Destroy(gameObject);
}
}
protected virtual void OnApplicationQuit()
{
_quitting = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment