Skip to content

ExclusiveGroups to group Entities and manage states

Sebastiano Mandalà edited this page Jan 27, 2021 · 13 revisions

Svelto grouping of entities is fundamental to query entities according to their states. Exclusive groups are best to be declared inside public static classes following this pattern:

public static class CharactersExclusiveGroups
{
public static ExclusiveGroup AISoldierGroup = new ExclusiveGroup();
public static ExclusiveGroup AIMonsterGroup = new ExclusiveGroup();
public static ExclusiveGroup PlayerSoldierGroup = new ExclusiveGroup();
public static ExclusiveGroup PlayerMonsterGroup = new ExclusiveGroup();

public static readonly ExclusiveGroup[] Soldiers = { PlayerSoldierGroup, AISoldierGroup};
public static readonly ExclusiveGroup[] Monsters = { PlayerMonsterGroup, AIMonsterGroup};
public static readonly ExclusiveGroup[] AI = { AISoldierGroup, AIMonsterGroup};
public static readonly ExclusiveGroup[] Players = { PlayerSoldierGroup, PlayerMonsterGroup};
}

this example is a bit advanced already as it shows how it is possible to use ExclusiveGroups to manage entities states too. For example is possible to switch entities between these "leaves" groups (AISoldierGroup, AIMonsterGroup, PlayerSoldierGroup, PlayerMonsterGroup) to change their behaviour at run time using the SwapEntityGroup method. Group aggregation is useful to apply shared behaviours between entities (which usually are linked to more abstracted engines)

groups of entities can be iterated using a pattern similar to:

foreach (var ((As, Bs, Cs, count), exclusiveGroupStruct) in entitiesDB.QueryEntities<A, B, C>(groups))
            {
                    for (uint i = 0; i < count; ++i)
                    {
                        ref var a= ref As[i];
                        ref var b= ref Bs[i];
                        ref var c= ref Cs[i];
                    }
            }

It's possible to push the concept of groups as state up to the point to use them as FSM states. Using the Add and Remove callbacks would be possible to decide what behaviours to trigger when an entity is added in a specific group and when an entity is removed from a specific group.