MailBoxComponentSystem.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using ETModel;
  5. namespace ETHotfix
  6. {
  7. [ObjectSystem]
  8. public class MailBoxComponentAwakeSystem : AwakeSystem<MailBoxComponent>
  9. {
  10. public override void Awake(MailBoxComponent self)
  11. {
  12. self.ActorInterceptType = ActorInterceptType.None;
  13. self.Queue.Clear();
  14. }
  15. }
  16. [ObjectSystem]
  17. public class MailBoxComponentAwake1System : AwakeSystem<MailBoxComponent, string>
  18. {
  19. public override void Awake(MailBoxComponent self, string actorInterceptType)
  20. {
  21. self.ActorInterceptType = actorInterceptType;
  22. self.Queue.Clear();
  23. }
  24. }
  25. [ObjectSystem]
  26. public class MailBoxComponentStartSystem : StartSystem<MailBoxComponent>
  27. {
  28. public override void Start(MailBoxComponent self)
  29. {
  30. self.HandleAsync();
  31. }
  32. }
  33. /// <summary>
  34. /// 挂上这个组件表示该Entity是一个Actor, 接收的消息将会队列处理
  35. /// </summary>
  36. public static class MailBoxComponentHelper
  37. {
  38. public static async ETTask AddLocation(this MailBoxComponent self)
  39. {
  40. await Game.Scene.GetComponent<LocationProxyComponent>().Add(self.Entity.Id, self.Entity.InstanceId);
  41. }
  42. public static async ETTask RemoveLocation(this MailBoxComponent self)
  43. {
  44. await Game.Scene.GetComponent<LocationProxyComponent>().Remove(self.Entity.Id);
  45. }
  46. public static void Add(this MailBoxComponent self, ActorMessageInfo info)
  47. {
  48. self.Queue.Enqueue(info);
  49. if (self.Tcs == null)
  50. {
  51. return;
  52. }
  53. var t = self.Tcs;
  54. self.Tcs = null;
  55. t.SetResult(self.Queue.Dequeue());
  56. }
  57. private static ETTask<ActorMessageInfo> GetAsync(this MailBoxComponent self)
  58. {
  59. if (self.Queue.Count > 0)
  60. {
  61. return ETTask.FromResult(self.Queue.Dequeue());
  62. }
  63. self.Tcs = new ETTaskCompletionSource<ActorMessageInfo>();
  64. return self.Tcs.Task;
  65. }
  66. public static async void HandleAsync(this MailBoxComponent self)
  67. {
  68. ActorMessageDispatherComponent actorMessageDispatherComponent = Game.Scene.GetComponent<ActorMessageDispatherComponent>();
  69. long instanceId = self.InstanceId;
  70. while (true)
  71. {
  72. if (self.InstanceId != instanceId)
  73. {
  74. return;
  75. }
  76. try
  77. {
  78. ActorMessageInfo info = await self.GetAsync();
  79. // 返回null表示actor已经删除,协程要终止
  80. if (info.Message == null)
  81. {
  82. return;
  83. }
  84. // 根据这个actor的类型分发给相应的ActorHandler处理
  85. await actorMessageDispatherComponent.Handle(self, info);
  86. }
  87. catch (Exception e)
  88. {
  89. Log.Error(e);
  90. }
  91. }
  92. }
  93. }
  94. }