ChildrenComponent.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using MongoDB.Bson.Serialization.Attributes;
  4. namespace Base
  5. {
  6. /// <summary>
  7. /// 父子层级信息
  8. /// </summary>
  9. public class ChildrenComponent : Component
  10. {
  11. [BsonIgnore]
  12. public Scene Parent { get; private set; }
  13. private readonly Dictionary<long, Scene> idChildren = new Dictionary<long, Scene>();
  14. private readonly Dictionary<string, Scene> nameChildren = new Dictionary<string, Scene>();
  15. [BsonIgnore]
  16. public int Count
  17. {
  18. get
  19. {
  20. return this.idChildren.Count;
  21. }
  22. }
  23. public void Add(Scene scene)
  24. {
  25. scene.GetComponent<ChildrenComponent>().Parent = this.GetOwner<Scene>();
  26. this.idChildren.Add(scene.Id, scene);
  27. this.nameChildren.Add(scene.Name, scene);
  28. }
  29. public Scene[] GetChildren()
  30. {
  31. return this.idChildren.Values.ToArray();
  32. }
  33. private void Remove(Scene scene)
  34. {
  35. this.idChildren.Remove(scene.Id);
  36. this.nameChildren.Remove(scene.Name);
  37. scene.Dispose();
  38. }
  39. public void Remove(long id)
  40. {
  41. Scene scene;
  42. if (!this.idChildren.TryGetValue(id, out scene))
  43. {
  44. return;
  45. }
  46. this.Remove(scene);
  47. }
  48. public void Remove(string name)
  49. {
  50. Scene scene;
  51. if (!this.nameChildren.TryGetValue(name, out scene))
  52. {
  53. return;
  54. }
  55. this.Remove(scene);
  56. }
  57. public override void Dispose()
  58. {
  59. if (this.Id == 0)
  60. {
  61. return;
  62. }
  63. base.Dispose();
  64. foreach (Scene scene in this.idChildren.Values.ToArray())
  65. {
  66. scene.Dispose();
  67. }
  68. this.Parent?.GetComponent<ChildrenComponent>().Remove(this.Id);
  69. }
  70. }
  71. public static class LevelHelper
  72. {
  73. public static void Add(this Scene scene, Scene child)
  74. {
  75. scene.GetComponent<ChildrenComponent>().Add(child);
  76. }
  77. public static void Remove(this Scene scene, long id)
  78. {
  79. scene.GetComponent<ChildrenComponent>().Remove(id);
  80. }
  81. public static void Remove(this Scene scene, string name)
  82. {
  83. scene.GetComponent<ChildrenComponent>().Remove(name);
  84. }
  85. }
  86. }