Component.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. using System;
  2. using MongoDB.Bson.Serialization.Attributes;
  3. namespace ETModel
  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 UNITY_EDITOR
  30. ECSView.SetParent(this);
  31. #endif
  32. }
  33. }
  34. [BsonIgnore]
  35. public bool IsDisposed
  36. {
  37. get
  38. {
  39. return this.InstanceId == 0;
  40. }
  41. }
  42. [BsonIgnore]
  43. private Component parent;
  44. [BsonIgnore]
  45. public Component Parent
  46. {
  47. get { return parent; }
  48. set
  49. {
  50. parent = value;
  51. #if UNITY_EDITOR
  52. ECSView.SetParent(this, parent);
  53. #endif
  54. }
  55. }
  56. public T GetParent<T>() where T : Component
  57. {
  58. return this.Parent as T;
  59. }
  60. [BsonIgnore]
  61. public Entity Entity
  62. {
  63. get
  64. {
  65. return this.Parent as Entity;
  66. }
  67. }
  68. protected Component()
  69. {
  70. #if UNITY_EDITOR
  71. ECSView.CreateView(this);
  72. #endif
  73. }
  74. public virtual void Dispose()
  75. {
  76. if (this.IsDisposed)
  77. {
  78. return;
  79. }
  80. // 触发Destroy事件
  81. Game.EventSystem.Destroy(this);
  82. Game.EventSystem.Remove(this.InstanceId);
  83. this.InstanceId = 0;
  84. #if UNITY_EDITOR
  85. if (this.IsFromPool)
  86. {
  87. Game.ObjectPool.Recycle(this);
  88. ECSView.ReturnPool(this);
  89. }
  90. else
  91. {
  92. ECSView.DestroyView(this);
  93. }
  94. #else
  95. if (this.IsFromPool)
  96. {
  97. Game.ObjectPool.Recycle(this);
  98. }
  99. #endif
  100. }
  101. public virtual void BeginSerialize()
  102. {
  103. }
  104. public virtual void EndDeSerialize()
  105. {
  106. }
  107. }
  108. }