ActorMessageDispatcherComponentSystem.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. namespace ET
  3. {
  4. [ObjectSystem]
  5. public class ActorMessageDispatcherComponentAwakeSystem: AwakeSystem<ActorMessageDispatcherComponent>
  6. {
  7. public override void Awake(ActorMessageDispatcherComponent self)
  8. {
  9. ActorMessageDispatcherComponent.Instance = self;
  10. self.Awake();
  11. }
  12. }
  13. [ObjectSystem]
  14. public class ActorMessageDispatcherComponentLoadSystem: LoadSystem<ActorMessageDispatcherComponent>
  15. {
  16. public override void Load(ActorMessageDispatcherComponent self)
  17. {
  18. self.Load();
  19. }
  20. }
  21. [ObjectSystem]
  22. public class ActorMessageDispatcherComponentDestroySystem: DestroySystem<ActorMessageDispatcherComponent>
  23. {
  24. public override void Destroy(ActorMessageDispatcherComponent self)
  25. {
  26. self.ActorMessageHandlers.Clear();
  27. ActorMessageDispatcherComponent.Instance = null;
  28. }
  29. }
  30. /// <summary>
  31. /// Actor消息分发组件
  32. /// </summary>
  33. public static class ActorMessageDispatcherComponentHelper
  34. {
  35. public static void Awake(this ActorMessageDispatcherComponent self)
  36. {
  37. self.Load();
  38. }
  39. public static void Load(this ActorMessageDispatcherComponent self)
  40. {
  41. self.ActorMessageHandlers.Clear();
  42. var types = Game.EventSystem.GetTypes(typeof (ActorMessageHandlerAttribute));
  43. foreach (Type type in types)
  44. {
  45. object obj = Activator.CreateInstance(type);
  46. IMActorHandler imHandler = obj as IMActorHandler;
  47. if (imHandler == null)
  48. {
  49. throw new Exception($"message handler not inherit IMActorHandler abstract class: {obj.GetType().FullName}");
  50. }
  51. Type messageType = imHandler.GetRequestType();
  52. self.ActorMessageHandlers.Add(messageType, imHandler);
  53. }
  54. }
  55. /// <summary>
  56. /// 分发actor消息
  57. /// </summary>
  58. public static async ETTask Handle(
  59. this ActorMessageDispatcherComponent self, Entity entity, object message, Action<IActorResponse> reply)
  60. {
  61. if (!self.ActorMessageHandlers.TryGetValue(message.GetType(), out IMActorHandler handler))
  62. {
  63. throw new Exception($"not found message handler: {message}");
  64. }
  65. await handler.Handle(entity, message, reply);
  66. }
  67. public static bool TryGetHandler(this ActorMessageDispatcherComponent self,Type type, out IMActorHandler actorHandler)
  68. {
  69. return self.ActorMessageHandlers.TryGetValue(type, out actorHandler);
  70. }
  71. }
  72. }