using UnityEngine; using System.Collections; namespace DevelopEngine { public class MonoSingleton : MonoBehaviour where T : MonoSingleton { private static T instance = null; public static T Instance { get { if (instance == null) { instance = FindObjectOfType(typeof(T)) as T; if (instance == null) { instance = new GameObject("_" + typeof(T).Name).AddComponent(); DontDestroyOnLoad(instance); } if (instance == null) Console.LogError("Failed to create instance of " + typeof(T).FullName + "."); } return instance; } } void OnApplicationQuit () { if (instance != null) instance = null; } public static T CreateInstance () { if (Instance != null) Instance.OnCreate(); return Instance; } protected virtual void OnCreate () { } } /// /// 无DontDestroyOnLoad属性的单例泛型模板 /// /// public class SingletonMono : MonoBehaviour where T : SingletonMono { private static T instance = null; public static T Instance { get { if (instance == null) { instance = FindObjectOfType(typeof(T)) as T; if (instance == null) { instance = new GameObject("_" + typeof(T).Name).AddComponent(); //DontDestroyOnLoad(instance); } if (instance == null) Console.LogError("Failed to create instance of " + typeof(T).FullName + "."); } return instance; } } void OnApplicationQuit() { if (instance != null) instance = null; } public static T CreateInstance() { if (Instance != null) Instance.OnCreate(); return Instance; } protected virtual void OnCreate() { } } }