ChildrenComponent.cs 1.9 KB
Newer Older
T
tanghai 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
using System.Collections.Generic;
using System.Linq;
using MongoDB.Bson.Serialization.Attributes;

namespace Base
{
	/// <summary>
	/// 父子层级信息
	/// </summary>
    public class ChildrenComponent : Component
    {
		[BsonIgnore]
		public Scene Parent { get; private set; }
		
		private readonly Dictionary<long, Scene> idChildren = new Dictionary<long, Scene>();
		
		private readonly Dictionary<string, Scene> nameChildren = new Dictionary<string, Scene>();

		[BsonIgnore]
		public int Count
		{
			get
			{
				return this.idChildren.Count;
			}
		}

		public void Add(Scene scene)
		{
			scene.GetComponent<ChildrenComponent>().Parent = this.GetOwner<Scene>();
			this.idChildren.Add(scene.Id, scene);
			this.nameChildren.Add(scene.Name, scene);
		}

		public Scene[] GetChildren()
		{
			return this.idChildren.Values.ToArray();
		}

		private void Remove(Scene scene)
		{
			this.idChildren.Remove(scene.Id);
			this.nameChildren.Remove(scene.Name);
			scene.Dispose();
		}

		public void Remove(long id)
		{
			Scene scene;
			if (!this.idChildren.TryGetValue(id, out scene))
			{
				return;
			}
			this.Remove(scene);
		}

		public void Remove(string name)
		{
			Scene scene;
			if (!this.nameChildren.TryGetValue(name, out scene))
			{
				return;
			}
			this.Remove(scene);
		}

		public override void Dispose()
		{
			if (this.Id == 0)
			{
				return;
			}

			base.Dispose();

			foreach (Scene scene in this.idChildren.Values.ToArray())
			{
				scene.Dispose();
			}

			this.Parent?.GetComponent<ChildrenComponent>().Remove(this.Id);
		}
    }

	public static class LevelHelper
	{
		public static void Add(this Scene scene, Scene child)
		{
			scene.GetComponent<ChildrenComponent>().Add(child);
		}

		public static void Remove(this Scene scene, long id)
		{
			scene.GetComponent<ChildrenComponent>().Remove(id);
		}

		public static void Remove(this Scene scene, string name)
		{
			scene.GetComponent<ChildrenComponent>().Remove(name);
		}
	}
}