SHARE
TWEET

Unity Singleton

apieceoffruit Nov 20th, 2019 81 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
  2. {
  3.     private static bool _shuttingDown = false;
  4.     private static readonly object _lock = new object();
  5.     private static T _instance;
  6.    
  7.     public static T Instance
  8.     {
  9.         get
  10.         {
  11.             if (_shuttingDown)
  12.             {
  13.                 Debug.LogWarning("[Singleton] Instance '" + typeof(T) +
  14.                     "' already destroyed. Returning null.");
  15.                 return null;
  16.             }
  17.  
  18.             lock (_lock)
  19.             {
  20.                 if (_instance != null) return _instance;
  21.                
  22.                 _instance = (T)FindObjectOfType(typeof(T));
  23.  
  24.                 if (_instance != null) return _instance;
  25.                
  26.                 var singletonObject = new GameObject();
  27.                 _instance = singletonObject.AddComponent<T>();
  28.                 singletonObject.name = typeof(T) + " (Singleton)";
  29.  
  30.                 DontDestroyOnLoad(singletonObject);
  31.  
  32.                 return _instance;
  33.             }
  34.         }
  35.     }
  36.  
  37.  
  38.     private void OnApplicationQuit()
  39.     {
  40.         _shuttingDown = true;
  41.     }
  42.  
  43.  
  44.     private void OnDestroy()
  45.     {
  46.         _shuttingDown = true;
  47.     }
  48. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top