-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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