ECS中的系统正常是读取一组输入组件,然后写入另一组输出组件,但是有些情况下需要用另一个系统另一组输入组件来写入相同的输出组件,Write groups提供了覆盖另一个系统的机制。
用Write groups可以让系统排除含有与写入组件相同的写组(WriteGroup)特性组件的实体,过滤条件:
- 系统有写入组件A
- 实体存在另一个组件B,该组件有WriteGroup A特性
例子:
两个组件:
public struct HealthComponent : IComponentData
{
public int Value;
}
public struct ColorComponent : IComponentData
{
public float4 Value;
}
系统:hp颜色修改系统 ComputeColorFromHealthSystem
(根据Health组件的值改变Color组件,比如小于10时变红色)
如果现在有道具可以让玩家无敌,则需要无敌标识组件InvincibleTagComponent和另一个系统将具备无敌标识组件的实体变成金色,所以hp颜色修改系统要过滤掉带InvincibleTagComponent组件的实体。使用Write Groups组件如下:
- 对无敌组件增加WriteGroup特性 [WriteGroup(typeof(ColorComponent))]
- 对hp颜色修改系统,对于写组件ColorComponent进行写组过滤,含带ColorComponent写组特性的组件的实体将被过滤,这里就会过滤掉含无敌组件的实体
...
protected override JobHandle OnUpdate(JobHandle inputDependencies) {
return Entities
.WithName("ComputeColor")
.WithEntityQueryOptions(EntityQueryOptions.FilterWriteGroup) // support write groups
.ForEach((ref ColorComponent color, in HealthComponent health) => {
// compute color here
}).Schedule(inputDependencies);
}
...