From acea7b2e728787a0d83bbf83c8c1f042d2c32e7e Mon Sep 17 00:00:00 2001 From: chai <215380520@qq.com> Date: Mon, 3 Jun 2024 10:15:45 +0800 Subject: + plugins project --- .../MonoGame.Extended.Entities/ComponentMapper.cs | 69 ++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Plugins/MonoGame.Extended/source/MonoGame.Extended.Entities/ComponentMapper.cs (limited to 'Plugins/MonoGame.Extended/source/MonoGame.Extended.Entities/ComponentMapper.cs') diff --git a/Plugins/MonoGame.Extended/source/MonoGame.Extended.Entities/ComponentMapper.cs b/Plugins/MonoGame.Extended/source/MonoGame.Extended.Entities/ComponentMapper.cs new file mode 100644 index 0000000..35b196c --- /dev/null +++ b/Plugins/MonoGame.Extended/source/MonoGame.Extended.Entities/ComponentMapper.cs @@ -0,0 +1,69 @@ +using System; +using MonoGame.Extended.Collections; + +namespace MonoGame.Extended.Entities +{ + public abstract class ComponentMapper + { + protected ComponentMapper(int id, Type componentType) + { + Id = id; + ComponentType = componentType; + } + + public int Id { get; } + public Type ComponentType { get; } + public abstract bool Has(int entityId); + public abstract void Delete(int entityId); + } + + public class ComponentMapper : ComponentMapper + where T : class + { + public event Action OnPut; + public event Action OnDelete; + + private readonly Action _onCompositionChanged; + + public ComponentMapper(int id, Action onCompositionChanged) + : base(id, typeof(T)) + { + _onCompositionChanged = onCompositionChanged; + Components = new Bag(); + } + + public Bag Components { get; } + + public void Put(int entityId, T component) + { + Components[entityId] = component; + _onCompositionChanged(entityId); + OnPut?.Invoke(entityId); + } + + public T Get(Entity entity) + { + return Get(entity.Id); + } + + public T Get(int entityId) + { + return Components[entityId]; + } + + public override bool Has(int entityId) + { + if (entityId >= Components.Count) + return false; + + return Components[entityId] != null; + } + + public override void Delete(int entityId) + { + Components[entityId] = null; + _onCompositionChanged(entityId); + OnDelete?.Invoke(entityId); + } + } +} -- cgit v1.1-26-g67d0