EventComponent.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Model
  4. {
  5. [EntityEvent(EntityEventId.EventComponent)]
  6. public class EventComponent : Component
  7. {
  8. private Dictionary<int, List<object>> allEvents;
  9. private void Awake()
  10. {
  11. this.Load();
  12. }
  13. private void Load()
  14. {
  15. this.allEvents = new Dictionary<int, List<object>>();
  16. Type[] types = DllHelper.GetAllTypes();
  17. foreach (Type type in types)
  18. {
  19. object[] attrs = type.GetCustomAttributes(typeof(EventAttribute), false);
  20. foreach (object attr in attrs)
  21. {
  22. EventAttribute aEventAttribute = (EventAttribute)attr;
  23. object obj = Activator.CreateInstance(type);
  24. if (!this.allEvents.ContainsKey(aEventAttribute.Type))
  25. {
  26. this.allEvents.Add(aEventAttribute.Type, new List<object>());
  27. }
  28. this.allEvents[aEventAttribute.Type].Add(obj);
  29. }
  30. }
  31. }
  32. public void Run(int type)
  33. {
  34. List<object> iEvents = null;
  35. if (!this.allEvents.TryGetValue(type, out iEvents))
  36. {
  37. return;
  38. }
  39. foreach (object obj in iEvents)
  40. {
  41. try
  42. {
  43. IEvent iEvent = (IEvent)obj;
  44. iEvent.Run();
  45. }
  46. catch (Exception e)
  47. {
  48. Log.Error(e.ToString());
  49. }
  50. }
  51. }
  52. public void Run<A>(int type, A a)
  53. {
  54. List<object> iEvents = null;
  55. if (!this.allEvents.TryGetValue(type, out iEvents))
  56. {
  57. return;
  58. }
  59. foreach (object obj in iEvents)
  60. {
  61. try
  62. {
  63. IEvent<A> iEvent = (IEvent<A>)obj;
  64. iEvent.Run(a);
  65. }
  66. catch (Exception err)
  67. {
  68. Log.Error(err.ToString());
  69. }
  70. }
  71. }
  72. public void Run<A, B>(int type, A a, B b)
  73. {
  74. List<object> iEvents = null;
  75. if (!this.allEvents.TryGetValue(type, out iEvents))
  76. {
  77. return;
  78. }
  79. foreach (object obj in iEvents)
  80. {
  81. try
  82. {
  83. IEvent<A, B> iEvent = (IEvent<A, B>)obj;
  84. iEvent.Run(a, b);
  85. }
  86. catch (Exception err)
  87. {
  88. Log.Error(err.ToString());
  89. }
  90. }
  91. }
  92. public void Run<A, B, C>(int type, A a, B b, C c)
  93. {
  94. List<object> iEvents = null;
  95. if (!this.allEvents.TryGetValue(type, out iEvents))
  96. {
  97. return;
  98. }
  99. foreach (object obj in iEvents)
  100. {
  101. try
  102. {
  103. IEvent<A, B, C> iEvent = (IEvent<A, B, C>)obj;
  104. iEvent.Run(a, b, c);
  105. }
  106. catch (Exception err)
  107. {
  108. Log.Error(err.ToString());
  109. }
  110. }
  111. }
  112. }
  113. }