AIComponentSystem.cs 2.7 KB

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