Use entity command buffers in Entities.ForEach
To use an entity command buffer (ECB) in the Entities.ForEach method, pass an EntityCommandBuffer parameter to the lambda expression. Only a small subset of EntityCommandBuffer methods are supported, and they have the [SupportedInEntitiesForEach] attribute:
Entity Instantiate(Entity entity)void DestroyEntity(Entity entity)void AddComponent<T>(Entity e, T component) where T : unmanaged, IComponentDatavoid SetComponent<T>(Entity e, T component) where T : unmanaged, IComponentDatavoid RemoveComponent<T>(Entity e)
For example, the following code does this:
- It checks each entity to find out whether its
HealthLevelis 0. - If true, it records a command to destroy the entity.
- It also specifies that the
EndSimulationEntityCommandBufferSystemmust play back the command.
public struct HealthLevel : IComponentData
{
public int Value;
}
partial class EcbParallelFor : SystemBase
{
protected override void OnUpdate()
{
Entities
.WithDeferredPlaybackSystem<EndSimulationEntityCommandBufferSystem>()
.ForEach(
(Entity entity, EntityCommandBuffer ecb, in HealthLevel health) =>
{
if (health.Value == 0)
{
ecb.DestroyEntity(entity);
}
}
).ScheduleParallel();
}
}
When you use any of these methods in a ForEach method, at runtime the compiler generates the code necessary to create, populate, play back, and dispose of an EntityCommandBuffer instance, or an EntityCommandBuffer.ParallelWriter instance, if ScheduleParallel is called.
Invoking these methods outside of ForEach() results in an exception.
Play back an entity command buffer
To pass an EntityCommandBuffer parameter to the ForEach method, you must also call one of the following methods to specify when you want to play back the commands:
- Deferred playback: Call
WithDeferredPlaybackSystem<T>, whereTidentifies the ECB system that plays back the commands. It must be a type that derives fromEntityCommandBufferSystem. - Immediate playback: call
WithImmediatePlaybackto execute the commands instantly after theForEachmethod has finished all iterations. You can only useWithImmediatePlaybackwithRun.
The compiler automatically generates code to create and dispose of any EntityCommandBuffer instances.