Singleton.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using System;
  2. using System.Reflection;
  3. using UnityEngine.Scripting;
  4. namespace Blue
  5. {
  6. [RequireDerived]
  7. public class Singleton<T> where T:Singleton<T>
  8. {
  9. private static T _instance;
  10. public static T Instance
  11. {
  12. get
  13. {
  14. if (_instance == null)
  15. {
  16. _instance = Init();
  17. }
  18. return _instance;
  19. }
  20. }
  21. private static T Init()
  22. {
  23. Type type = typeof(T);
  24. ConstructorInfo[] ctorArr=type.GetConstructors(BindingFlags.Instance|BindingFlags.NonPublic);
  25. if (ctorArr.Length==0)
  26. {
  27. throw new Exception("Non Public Contstrucor Not Found In "+type.FullName);
  28. }
  29. ConstructorInfo ctor=Array.Find(ctorArr,c=> c.GetParameters().Length==0);
  30. if (ctor == null)
  31. {
  32. throw new Exception("Non Public Contstrucor Not Found In " + type.FullName);
  33. }
  34. _instance=ctor.Invoke(null) as T;
  35. return _instance;
  36. }
  37. }
  38. }