我想创建一个实体-组件-系统示例。我有像
internal struct Position : IComponent
{
public int X { get; set; }
public int Y { get; set; }
}
和
internal struct Movementspeed : IComponent
{
public float Value { get; set; }
}
哪个实施
internal interface IComponent
{
}
在遍历组件时,我想尽快找到它们。我考虑过创建一个字典,将组件类型作为键,将组件作为值。
internal class ComponentCollection
{
public ComponentCollection()
{
components = new Dictionary<Type, object>();
}
private Dictionary<Type, object> components;
public void AddComponent<T>(T component) // add a new component
{
Type componentType = typeof(T);
components.Add(componentType, component as IComponent);
}
public void RemoveComponent(Type componentType) // remove the component by type
{
components.Remove(componentType);
}
public bool TryGetComponent<T>(out T component) // get the specified component
{
try
{
Type componentType = typeof(T);
component = (T)components[componentType];
return true;
}
catch (Exception)
{
component = default(T);
return false;
}
}
}
有两个问题出现。
如果有人使用
float movementspeed
并尝试添加一个新的 MovementspeedComponent 怎么办?拥有两个浮点数会引发重复键异常。我只能添加实现IComponent
接口的自定义结构组件以防止重复。当我尝试修改组件时,它们不会被引用修改
private static void Main(string[] args) { ComponentCollection components = new ComponentCollection(); components.AddComponent(new Position()); components.AddComponent(new Movementspeed()); if (components.TryGetComponent(out Position fooPosition)) { fooPosition.X++; Console.WriteLine(fooPosition.X); // prints 1 } if (components.TryGetComponent(out Position barPosition)) { Console.WriteLine(barPosition.X); // prints 0 } Console.ReadLine(); }
有什么建议么?