ActorMessageDispatcherComponentSystem.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections.Generic;
  3. using ETModel;
  4. namespace ETHotfix
  5. {
  6. [ObjectSystem]
  7. public class ActorMessageDispatcherComponentStartSystem: AwakeSystem<ActorMessageDispatcherComponent>
  8. {
  9. public override void Awake(ActorMessageDispatcherComponent self)
  10. {
  11. self.Awake();
  12. }
  13. }
  14. [ObjectSystem]
  15. public class ActorMessageDispatcherComponentLoadSystem: LoadSystem<ActorMessageDispatcherComponent>
  16. {
  17. public override void Load(ActorMessageDispatcherComponent self)
  18. {
  19. self.Load();
  20. }
  21. }
  22. /// <summary>
  23. /// Actor消息分发组件
  24. /// </summary>
  25. public static class ActorMessageDispatcherComponentHelper
  26. {
  27. public static void Awake(this ActorMessageDispatcherComponent self)
  28. {
  29. self.Load();
  30. }
  31. public static void Load(this ActorMessageDispatcherComponent self)
  32. {
  33. AppType appType = StartConfigComponent.Instance.StartConfig.AppType;
  34. self.ActorMessageHandlers.Clear();
  35. List<Type> types = Game.EventSystem.GetTypes(typeof(ActorMessageHandlerAttribute));
  36. types = Game.EventSystem.GetTypes(typeof (ActorMessageHandlerAttribute));
  37. foreach (Type type in types)
  38. {
  39. object[] attrs = type.GetCustomAttributes(typeof(ActorMessageHandlerAttribute), false);
  40. if (attrs.Length == 0)
  41. {
  42. continue;
  43. }
  44. ActorMessageHandlerAttribute messageHandlerAttribute = (ActorMessageHandlerAttribute) attrs[0];
  45. if (!messageHandlerAttribute.Type.Is(appType))
  46. {
  47. continue;
  48. }
  49. object obj = Activator.CreateInstance(type);
  50. IMActorHandler imHandler = obj as IMActorHandler;
  51. if (imHandler == null)
  52. {
  53. throw new Exception($"message handler not inherit IMActorHandler abstract class: {obj.GetType().FullName}");
  54. }
  55. Type messageType = imHandler.GetMessageType();
  56. self.ActorMessageHandlers.Add(messageType, imHandler);
  57. }
  58. }
  59. /// <summary>
  60. /// 分发actor消息
  61. /// </summary>
  62. public static async ETTask Handle(
  63. this ActorMessageDispatcherComponent self, Entity entity, ActorMessageInfo actorMessageInfo)
  64. {
  65. if (!self.ActorMessageHandlers.TryGetValue(actorMessageInfo.Message.GetType(), out IMActorHandler handler))
  66. {
  67. throw new Exception($"not found message handler: {MongoHelper.ToJson(actorMessageInfo.Message)}");
  68. }
  69. await handler.Handle(actorMessageInfo.Session, entity, actorMessageInfo.Message);
  70. }
  71. }
  72. }