Adding components in ITriggerEventsJob

Hi,
For my game I need to add a component on collision/when a trigger is hit.
For this I’ve been using the ITriggerEventsJob, which works well if there is only 1 collision event.
But sometimes multiple events report the same entity and this seems to cause an issue when the EntityCommandBuffer is played back.
I suspect this is because it’s now trying to add the same component twice (ecs errors aren’t the most descriptive).
Does anyone have an idea on how to solve this issue?

(Simple example of what I mean)

struct TriggerJob : ITriggerEventsJob
{
    public EntityCommandBuffer commandBuffer;

    public void Execute(TriggerEvent triggerEvent)
    {
        var entA = triggerEvent.Entities.EntityA;
        var entB = triggerEvent.Entities.EntityB;

        commandBuffer.AddComponent(entA, new IsTriggeredEvent() { data = 5 });
        commandBuffer.AddComponent(entB, new IsTriggeredEvent() { data = 5 });
    }
}

Hi,
Can you share the error you’re seeing? Adding a component that already exists on an entity through the command buffer should result in just setting the value.

Also, can you share which version of Entities you are using?

Thanks!

1 Like

Maybe change EntityCommandBuffer to EntityCommandBuffer.ParallelWriter ?

EntityCommandBuffer.ParallelWriter is meant for multithreaded jobs and requires a Execute([ChunkIndexInQuery] int ciq.

Which you can’t do in a ITriggerEventsJob.

Unity in its own ECS samples repo changes components in ITriggerEventsJob’s like this:

public ComponentLookup<PhysicsGravityFactor> PhysicsGravityFactorGroup;
...
var component = PhysicsGravityFactorGroup[dynamicEntity];
component.Value = triggerGravityComponent.GravityFactor;

I was also interested in how to destroy or create an entity on collision with a command buffer only once. I guess it’s not possible considering you can have multiple collision events, and they already happened by the time you read them.

Unless you use one of the ComponentLookup component value sets (which are instant) to mark this pair as “solved” so subsequent trigger calls you can return early from.