AIComponentSystem.cs 2.3 KB

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