Component.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using MongoDB.Bson.Serialization.Attributes;
  2. using System;
  3. namespace KYFramework
  4. {
  5. [BsonIgnoreExtraElements]
  6. public abstract class Component : Object , IDisposable
  7. {
  8. [BsonIgnore]
  9. public long InstanceId { get; set; }
  10. [BsonIgnore]
  11. protected bool isFromPool;
  12. [BsonIgnore]
  13. public bool IsFromPool
  14. {
  15. get
  16. {
  17. return isFromPool;
  18. }
  19. set
  20. {
  21. isFromPool = value;
  22. if (!this.isFromPool) return;
  23. if(InstanceId == 0)
  24. InstanceId = IdGenerater.GenerateInstanceId();
  25. }
  26. }
  27. [BsonIgnore]
  28. public bool IsDisposed
  29. {
  30. get
  31. {
  32. return this.InstanceId == 0;
  33. }
  34. }
  35. private Component parent;
  36. [BsonIgnore]
  37. public Component Parent
  38. {
  39. get
  40. {
  41. return this.parent;
  42. }
  43. set
  44. {
  45. parent = value;
  46. }
  47. }
  48. public T GetParent<T>() where T : Component
  49. {
  50. return this.Parent as T;
  51. }
  52. [BsonIgnore]
  53. public Entity Entity
  54. {
  55. get
  56. {
  57. return this.Parent as Entity;
  58. }
  59. }
  60. protected Component()
  61. {
  62. this.InstanceId = IdGenerater.GenerateInstanceId();
  63. }
  64. public virtual void Dispose()
  65. {
  66. if (this.IsDisposed)
  67. {
  68. return;
  69. }
  70. // 触发Destroy事件
  71. Game.EventSystem.Destroy(this);
  72. Game.EventSystem.Remove(this.InstanceId);
  73. this.InstanceId = 0;
  74. if (this.IsFromPool)
  75. {
  76. Game.ObjectPool.Recycle(this);
  77. }
  78. else
  79. {
  80. }
  81. }
  82. public override void EndInit()
  83. {
  84. Game.EventSystem.Deserialize(this);
  85. }
  86. public override string ToString()
  87. {
  88. return MongoHelper.ToJson(this);
  89. }
  90. }
  91. }