using UnityEngine; using System.Collections; public abstract class Singleton where T : new() { private static T _instance; static object _lock = new object(); public static T Instance { get { if (_instance == null) { lock (_lock) { if (_instance == null) _instance = new T(); } } return _instance; } } } /// /// Be aware this will not prevent a non singleton constructor5. /// such as `T myT = new T();` /// To prevent that, add `protected T () {}` to your singleton class. /// public class UnitySingleton : MonoBehaviour where T : MonoBehaviour { private static T _instance; private static object _lock = new object (); public static T Instance { get { lock (_lock) { if (applicationIsQuitting) { return null; } if (_instance == null) { _instance = (T)FindObjectOfType (typeof(T)); if (_instance == null) { string goName = typeof(T).ToString (); GameObject go = GameObject.Find (goName); if (go == null) { go = new GameObject (); _instance = go.AddComponent (); go.name = "(singleton) " + typeof(T).ToString (); //go.hideFlags = HideFlags.HideAndDontSave; DontDestroyOnLoad (go); } } else { } } return _instance; } } } private static bool applicationIsQuitting = false; // private static bool ClearMode = false; public static void DestorySingleton () { lock (_lock) { applicationIsQuitting = true; if (_instance != null) { // ClearMode = true; GameObject.Destroy (_instance.gameObject); _instance = null; } } } // public void OnDestroy() { // //Debug.LogError ("unitySingle OnDestroy"); // lock (_lock) { // applicationIsQuitting = true; // if (_instance != null) { // GameObject.Destroy (_instance.gameObject); // _instance = null; // } // } // } } public class UnitySingletonLoadDestory : MonoBehaviour where T : MonoBehaviour { private static T _instance; private static object _lock = new object (); public static T Instance { get { if (applicationIsQuitting) { return null; } lock (_lock) { if (_instance == null) { _instance = (T)FindObjectOfType (typeof(T)); if (_instance == null) { string goName = typeof(T).ToString (); GameObject go = GameObject.Find (goName); if (go == null) { go = new GameObject (); _instance = go.AddComponent (); go.name = "(singleton) " + typeof(T).ToString (); //go.hideFlags = HideFlags.HideAndDontSave; go.hideFlags = HideFlags.DontSave; } } else { } } return _instance; } } } private static bool applicationIsQuitting = false; public static void DestorySingleton () { lock (_lock) { applicationIsQuitting = true; if (_instance != null) { GameObject.Destroy (_instance.gameObject); _instance = null; } } } public void OnDestroy() { lock (_lock) { applicationIsQuitting = true; if (_instance != null) { GameObject.Destroy (_instance.gameObject); _instance = null; } } } }