Singleton.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Reflection;
  5. namespace WildAttack
  6. {
  7. /// <summary>
  8. /// 单例基类
  9. /// </summary>
  10. /// <typeparam name="T"></typeparam>
  11. public class Singleton<T> : ISingletonExpand where T : Singleton<T>, new()
  12. {
  13. private static T instance;
  14. public static T GetInstance()
  15. {
  16. if (instance == null)
  17. {
  18. instance = new T();
  19. SingletonManager.singletons.Add(instance);
  20. }
  21. return instance;
  22. }
  23. public void ClearSingleton()
  24. {
  25. if (instance == this)
  26. {
  27. instance = null;
  28. }
  29. }
  30. }
  31. public interface ISingletonExpand
  32. {
  33. void ClearSingleton();
  34. }
  35. public class SingletonManager
  36. {
  37. public static HashSet<ISingletonExpand> singletons = new();
  38. public static void Clear()
  39. {
  40. foreach (var item in singletons)
  41. {
  42. item.ClearSingleton();
  43. }
  44. singletons.Clear();
  45. }
  46. }
  47. }