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 the entity 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)

you can iterate using:

void ExecuteOnAllEntities<T>(ExclusiveGroup[] groups, EntitiesAction<T> action) where T : IEntityStruct;

or simply:

foreach (ExclusiveGroup agentsGroup in ServerAIExclusiveGroups.MovingAgentGroups)
{
     int numEntities = 0;
     var entities = entitiesDB.QueryEntities<ServerAgentSteeringEntityViewStruct>(agentsGroup, out numEntities);
     
     for (int i = 0; i < numEntities; i++)
     {
         ServerAgentSteeringEntityViewStruct serverAgentSteeringEntityViewStruct = entities[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.

https://github.com/sebas77/Svelto.ECS/wiki/Why-engines-can-support-callbacks-on-entity-added-and-removed