NumericWatcherComponent.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ET
  4. {
  5. public struct NumericWatcherInfo
  6. {
  7. public int SceneType { get; }
  8. public INumericWatcher INumericWatcher { get; }
  9. public NumericWatcherInfo(int sceneType, INumericWatcher numericWatcher)
  10. {
  11. this.SceneType = sceneType;
  12. this.INumericWatcher = numericWatcher;
  13. }
  14. }
  15. /// <summary>
  16. /// 监视数值变化组件,分发监听
  17. /// </summary>
  18. [CodeProcess]
  19. public class NumericWatcherComponent : Singleton<NumericWatcherComponent>, ISingletonAwake
  20. {
  21. private readonly Dictionary<int, List<NumericWatcherInfo>> allWatchers = new();
  22. public void Awake()
  23. {
  24. HashSet<Type> types = CodeTypes.Instance.GetTypes(typeof(NumericWatcherAttribute));
  25. foreach (Type type in types)
  26. {
  27. object[] attrs = type.GetCustomAttributes(typeof(NumericWatcherAttribute), false);
  28. foreach (object attr in attrs)
  29. {
  30. NumericWatcherAttribute numericWatcherAttribute = (NumericWatcherAttribute)attr;
  31. INumericWatcher obj = (INumericWatcher)Activator.CreateInstance(type);
  32. NumericWatcherInfo numericWatcherInfo = new(numericWatcherAttribute.SceneType, obj);
  33. if (!this.allWatchers.ContainsKey(numericWatcherAttribute.NumericType))
  34. {
  35. this.allWatchers.Add(numericWatcherAttribute.NumericType, new List<NumericWatcherInfo>());
  36. }
  37. this.allWatchers[numericWatcherAttribute.NumericType].Add(numericWatcherInfo);
  38. }
  39. }
  40. }
  41. public void Run(Unit unit, NumbericChange args)
  42. {
  43. List<NumericWatcherInfo> list;
  44. if (!this.allWatchers.TryGetValue(args.NumericType, out list))
  45. {
  46. return;
  47. }
  48. int unitDomainSceneType = unit.IScene.SceneType;
  49. foreach (NumericWatcherInfo numericWatcher in list)
  50. {
  51. if (!SceneTypeSingleton.IsSame(numericWatcher.SceneType, unitDomainSceneType))
  52. {
  53. continue;
  54. }
  55. numericWatcher.INumericWatcher.Run(unit, args);
  56. }
  57. }
  58. }
  59. }