AIComponentSystem.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using UnityEngine;
  3. namespace ET
  4. {
  5. [Timer(TimerType.AITimer)]
  6. public class AITimer: ATimer<AIComponent>
  7. {
  8. public override void Run(AIComponent self)
  9. {
  10. try
  11. {
  12. self.Check();
  13. }
  14. catch (Exception e)
  15. {
  16. Log.Error($"move timer error: {self.Id}\n{e}");
  17. }
  18. }
  19. }
  20. [ObjectSystem]
  21. public class AIComponentAwakeSystem: AwakeSystem<AIComponent, int>
  22. {
  23. public override void Awake(AIComponent self, int aiConfigId)
  24. {
  25. self.AIConfigId = aiConfigId;
  26. self.Timer = TimerComponent.Instance.NewRepeatedTimer(1000, TimerType.AITimer, self);
  27. }
  28. }
  29. [ObjectSystem]
  30. public class AIComponentDestroySystem: DestroySystem<AIComponent>
  31. {
  32. public override void Destroy(AIComponent self)
  33. {
  34. TimerComponent.Instance?.Remove(ref self.Timer);
  35. self.CancellationToken?.Cancel();
  36. self.CancellationToken = null;
  37. self.Current = 0;
  38. }
  39. }
  40. public static class AIComponentSystem
  41. {
  42. public static void Check(this AIComponent self)
  43. {
  44. if (self.Parent == null)
  45. {
  46. TimerComponent.Instance.Remove(ref self.Timer);
  47. return;
  48. }
  49. var oneAI = AIConfigCategory.Instance.AIConfigs[self.AIConfigId];
  50. foreach (AIConfig aiConfig in oneAI.Values)
  51. {
  52. AIDispatcherComponent.Instance.AIHandlers.TryGetValue(aiConfig.Name, out AAIHandler aaiHandler);
  53. if (aaiHandler == null)
  54. {
  55. Log.Error($"not found aihandler: {aiConfig.Name}");
  56. continue;
  57. }
  58. int ret = aaiHandler.Check(self, aiConfig);
  59. if (ret != 0)
  60. {
  61. continue;
  62. }
  63. if (self.Current == aiConfig.Id)
  64. {
  65. break;
  66. }
  67. self.Cancel(); // 取消之前的行为
  68. ETCancellationToken cancellationToken = new ETCancellationToken();
  69. self.CancellationToken = cancellationToken;
  70. self.Current = aiConfig.Id;
  71. aaiHandler.Execute(self, aiConfig, cancellationToken).Coroutine();
  72. return;
  73. }
  74. }
  75. private static void Cancel(this AIComponent self)
  76. {
  77. self.CancellationToken?.Cancel();
  78. self.Current = 0;
  79. self.CancellationToken = null;
  80. }
  81. }
  82. }