AIComponentSystem.cs 2.8 KB

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