【发布时间】:2019-03-09 18:13:33
【问题描述】:
在Entity Component Systems 中,实体与组件中的数据保持关系,然后每个组件都可以由多个系统操作。每个系统都可以依赖于许多组件。
目前,我在一个基类中实现系统,并完成了查找组件并将其耦合到同一个实体的大部分繁重工作。其中很多都是使用泛型完成的,而且效果很好。
public abstract class System<T1>: System
where T1: Component
{
public override void Update( long delta )
{
ComponentStorage<Component> componentStorage1 = GetComponentStorageByType<T1>( );
List<Entity> entities = GetEntities( );
if ( componentStorage1 == null )
return;
entities.ForEach( e =>
{
int index = entities.IndexOf( e );
if ( componentStorage1[ index ] == null )
return;
Update( (T1) componentStorage1[ index ], delta );
} );
}
protected abstract void Update( T1 component1, long delta );
}
继承的类覆盖了名为 Update 的方法,我通过存储中的 update 方法将实例化的组件传递给该方法。
class TestSystem1: System<TestComponent1>
{
protected override void Update( TestComponent1 component1, long delta )
{
Console.WriteLine( $"{component1.Count++}" );
}
}
这适用于只有一个组件的系统。如果系统有多个组件,我将不得不为许多组件添加另一个通用 Tn,这意味着实现最多无限数量的类。
我研究了可变数量的通用参数,C++11 has it 但 C# does not。
我可能可以让反射发挥作用,但在我用尽所有其他选择之前,我宁愿不这样做。
有没有可以满足我需求的设计?我希望它保留继承的类最完整 - 调用一个覆盖、受保护的 Update 方法(或类似方法)并将一个已经转换的组件交给它。
【问题讨论】:
标签: c#