Entities in Query

Entities in Query, how to handle entities in queries correctly and what to bear in mind.

We need to have another serious talk about what you can and should and should not do in Querys! So sit down and listen!

In principle, we recommend the use of a CommandBuffer when it comes to creating or deleting entities in a query or changing their structure. Or to simply make these changes outside a query. Changes to component values are never a problem.

Create in Query

Creating entities in Queries is harmless for the time being, nothing can go wrong.

world.Query(queryDesc, (ref DwarfSpawner spawner) => {
    
    if(!spawner.CanSpawnDwarf()) return;
    world.Create<Dwarf, Position, Velocity>();
});

Modify in Query

You can usually edit existing data on entities without any problems.

world.Query(queryDesc, (ref Dwarf dwarf) => {
    dwarf.Health++;  // healing the dwarf
});

But there is one case where you really have to be careful and that is when you add or remove components.

world.Query(queryDesc, (Entity entity, ref Dwarf dwarf) => {
    entity.Add<Pickaxe>();
    entity.Remove<Helmet>();
});

Delete in Query

This is where it gets interesting and fun. Let's take a look at this case.

world.Query(queryDesc, (in Entity entity, ref Dwarf dwarf) => {
    
    if(!CanDeleteDwarf()) return;  // A random chance
    world.Destroy(RandomDwarf());
});

In such a case, we should use the CommandBuffer or maintain our own list of entities, which we then delete ourselves after the Query. What works, however, is if we have a deterministic order when deleting.

world.Query(queryDesc, (in Entity entity, ref Dwarf dwarf) => {
    world.Destroy(entity);
});

What also works, of course, is deleting entities in a query that we are not currently iterating over.

world.Query(queryDesc, (in Entity entity, ref Dwarf dwarf) => {
    world.Destroy(RandomElf());
});

Why is that?

The reason

You're probably wondering why we don't just install a few security checks to prevent this kind of behavior? Good question!

This has pros and cons, one advantage is clean code and performance. In the future Arch will get optional security checks.

Last updated

Was this helpful?