56 lines
2.0 KiB
C#
56 lines
2.0 KiB
C#
|
using System;
|
|||
|
using System.Collections.Generic;
|
|||
|
using System.Linq;
|
|||
|
|
|||
|
namespace Encompass
|
|||
|
{
|
|||
|
public class Entity
|
|||
|
{
|
|||
|
public readonly static List<Component> Empty = new List<Component>();
|
|||
|
|
|||
|
public readonly int id;
|
|||
|
|
|||
|
private readonly Dictionary<Type, List<Component>> componentBag = new Dictionary<Type, List<Component>>();
|
|||
|
private readonly Dictionary<Type, List<Component>> activeComponents = new Dictionary<Type, List<Component>>();
|
|||
|
|
|||
|
public Entity(int id) {
|
|||
|
this.id = id;
|
|||
|
}
|
|||
|
|
|||
|
public TComponent AddComponent<TComponent>() where TComponent : Component, new() {
|
|||
|
TComponent component = new TComponent();
|
|||
|
|
|||
|
if (!componentBag.ContainsKey(typeof(TComponent))) {
|
|||
|
var componentList = new List<Component>();
|
|||
|
var activeComponentList = new List<Component>();
|
|||
|
componentBag.Add(typeof(TComponent), componentList);
|
|||
|
activeComponents.Add(typeof(TComponent), activeComponentList);
|
|||
|
componentList.Add(component);
|
|||
|
activeComponentList.Add(component);
|
|||
|
} else {
|
|||
|
componentBag[typeof(TComponent)].Add(component);
|
|||
|
activeComponents[typeof(TComponent)].Add(component);
|
|||
|
}
|
|||
|
|
|||
|
return component;
|
|||
|
}
|
|||
|
|
|||
|
public IEnumerable<TComponent> GetComponents<TComponent>() where TComponent : Component {
|
|||
|
if (activeComponents.ContainsKey(typeof(TComponent))) {
|
|||
|
return activeComponents[typeof(TComponent)].Cast<TComponent>();
|
|||
|
} else {
|
|||
|
return Enumerable.Empty<TComponent>();
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
public TComponent GetComponent<TComponent>() where TComponent : Component {
|
|||
|
return GetComponents<TComponent>().First();
|
|||
|
}
|
|||
|
|
|||
|
public bool HasComponent<TComponent>() where TComponent : Component {
|
|||
|
return activeComponents.ContainsKey(typeof(TComponent)) &&
|
|||
|
activeComponents[typeof(TComponent)].Count != 0;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|