批处理对象复用
public class GameEntityFactory
{
private readonly IECSWorld world;
private readonly BatchEntityBuilder playerBatch;
private readonly BatchEntityBuilder enemyBatch;
private readonly BatchProcessor upgradeBatch;
public GameEntityFactory(IECSWorld world)
{
this.world = world;
// 缓存常用的批处理对象
playerBatch = world.GetBatchBuilder(false);
enemyBatch = world.GetBatchBuilder(false);
upgradeBatch = new BatchProcessor();
SetupBatches();
}
private void SetupBatches()
{
// 预配置玩家批处理
playerBatch.AddComponent(new Health(100))
.AddComponent(new PgdPosition())
.AddComponent(new Velocity())
.AddTag<PlayerTag>()
.AddTag<AliveTag>();
// 预配置敌人批处理
enemyBatch.AddComponent(new Health(50))
.AddComponent(new PgdPosition())
.AddComponent(new AIComponent())
.AddTag<EnemyTag>()
.AddTag<AliveTag>();
// 预配置升级批处理
upgradeBatch.AddComponent(new LevelUpEffect())
.AddTag<LevelUpTag>();
}
public IEntity CreatePlayer(Vector3 position)
{
ref var pos = ref playerBatch.GetComponent<PgdPosition>();
pos.vec3 = position;
return playerBatch.CreateEntity();
}
public IEntity CreateEnemy(Vector3 position)
{
ref var pos = ref enemyBatch.GetComponent<PgdPosition>();
pos.vec3 = position;
return enemyBatch.CreateEntity();
}
public void UpgradeEntity(IEntity entity)
{
upgradeBatch.ProcessOn(entity);
}
public void Dispose()
{
playerBatch.ReleaseBatch();
enemyBatch.ReleaseBatch();
}
}