Skip to content

Instantly share code, notes, and snippets.

@abirpahlwan
Created October 2, 2022 23:21
Show Gist options
  • Save abirpahlwan/e1ce7324aa900b5b7b926bc84ebcddba to your computer and use it in GitHub Desktop.
Save abirpahlwan/e1ce7324aa900b5b7b926bc84ebcddba to your computer and use it in GitHub Desktop.
Unity Singleton
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour {
// Check to see if we're about to be destroyed.
private static bool _ShuttingDown = false;
private static object _Lock = new object();
private static T _Instance;
/// <summary>
/// Access singleton instance through this propriety.
/// </summary>
public static T Instance {
get {
if (_ShuttingDown) {
Debug.LogWarning("[Singleton] Instance " + typeof(T) + " already destroyed. Returning null.");
return null;
}
lock (_Lock) {
if (_Instance == null) {
// Search for existing instance.
_Instance = (T) FindObjectOfType(typeof(T));
// Create new instance if one doesn't already exist.
if (_Instance == null) {
// Need to create a new GameObject to attach the singleton to.
var singletonObject = new GameObject();
_Instance = singletonObject.AddComponent<T>();
singletonObject.name = typeof(T).ToString() + " (Singleton)";
// Make instance persistent.
DontDestroyOnLoad(singletonObject);
}
}
return _Instance;
}
}
}
private void OnApplicationQuit() {
_ShuttingDown = true;
}
private void OnDestroy() {
_ShuttingDown = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment