Component.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. using ETModel;
  2. using MongoDB.Bson.Serialization.Attributes;
  3. namespace ETHotfix
  4. {
  5. [BsonIgnoreExtraElements]
  6. public abstract class Component : Object, IDisposable, IComponentSerialize
  7. {
  8. // 只有Game.EventSystem.Add方法中会设置该值,如果new出来的对象不想加入Game.EventSystem中,则需要自己在构造函数中设置
  9. [BsonIgnore]
  10. public long InstanceId { get; protected set; }
  11. [BsonIgnore]
  12. private bool isFromPool;
  13. [BsonIgnore]
  14. public bool IsFromPool
  15. {
  16. get
  17. {
  18. return this.isFromPool;
  19. }
  20. set
  21. {
  22. this.isFromPool = value;
  23. if (!this.isFromPool)
  24. {
  25. return;
  26. }
  27. this.InstanceId = IdGenerater.GenerateId();
  28. Game.EventSystem.Add(this);
  29. if (Define.IsEditorMode)
  30. ECSView.SetParent(this);
  31. }
  32. }
  33. [BsonIgnore]
  34. public bool IsDisposed
  35. {
  36. get
  37. {
  38. return this.InstanceId == 0;
  39. }
  40. }
  41. [BsonIgnore]
  42. private Component parent;
  43. [BsonIgnore]
  44. public Component Parent
  45. {
  46. get { return parent; }
  47. set
  48. {
  49. parent = value;
  50. if (Define.IsEditorMode)
  51. ECSView.SetParent(this, parent);
  52. }
  53. }
  54. public T GetParent<T>() where T : Component
  55. {
  56. return this.Parent as T;
  57. }
  58. [BsonIgnore]
  59. public Entity Entity
  60. {
  61. get
  62. {
  63. return this.Parent as Entity;
  64. }
  65. }
  66. protected Component()
  67. {
  68. if (Define.IsEditorMode)
  69. ECSView.CreateView(this);
  70. }
  71. public virtual void Dispose()
  72. {
  73. if (this.IsDisposed)
  74. {
  75. return;
  76. }
  77. // 触发Destroy事件
  78. Game.EventSystem.Destroy(this);
  79. Game.EventSystem.Remove(this.InstanceId);
  80. this.InstanceId = 0;
  81. if (this.IsFromPool)
  82. Game.ObjectPool.Recycle(this);
  83. if (Define.IsEditorMode)
  84. {
  85. if (this.IsFromPool)
  86. ECSView.ReturnPool(this);
  87. else
  88. ECSView.DestroyView(this);
  89. }
  90. }
  91. public virtual void BeginSerialize()
  92. {
  93. }
  94. public virtual void EndDeSerialize()
  95. {
  96. }
  97. }
  98. }