1、非Mono单例:
1 using System; 2 using System.Reflection; 3 using System.Collections.Generic; 4 5 public static class Singleton<T> where T : class 6 { 7 static volatile T _instance; 8 static object _lock = new object(); 9 10 static Singleton() 11 { 12 } 13 14 public static T Get() 15 { 16 if (_instance == null) 17 { 18 lock (_lock) 19 { 20 if (_instance == null) 21 { 22 ConstructorInfo constructor = null; 23 try 24 { 25 constructor = typeof(T).GetConstructor(BindingFlags.Instance | 26 BindingFlags.NonPublic, null, new Type[0], null); 27 } 28 catch (Exception e) 29 { 30 throw e; 31 } 32 33 if (constructor == null || constructor.IsAssembly) 34 { 35 throw new Exception(string.Format("A private or protected constructor is missing for '{0}'.", typeof(T).Name)); 36 } 37 38 _instance = (T)constructor.Invoke(null); 39 } 40 } 41 } 42 return _instance; 43 } 44 }
调用方法:Singleton<XXX>.Get(),XXX表示非继承MonoBehavior的类的类名。
2、Mono单例:
1 using System; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public static class MonoSingleton<T> where T : MonoBehaviour 6 { 7 private static T _instance; 8 9 public static T Get() 10 { 11 if (_instance == null) 12 { 13 _instance = UnityEngine.Object.FindObjectOfType<T>(); 14 } 15 16 return _instance; 17 } 18 }
调用方法:MonoSingleton<XXX>.Get(),XXX表示继承MonoBehavior的类的类名。