Skip to content

ExclusiveGroups to group Entities and manage states

Sebastiano Mandalà edited this page Nov 6, 2018 · 13 revisions

The new version of Svelto forces the use of groups when entities are built and queries, plus now is mandatory to use ExclusiveGroups when an entity must be set in a group. 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 actually quite advanced already and I show it to you to demonstrate how you can use ExclusiveGroups to manage entities states too. Having an engine for each state (soldier managed by AI, soldier managed by Player, monster managed by AI and monster managed by player) you can switch the entity between these groups to change their behavior using the SwapEntityGroup method. The very nice pattern is that through the arrays Soldiers, Monsters, AI and Players you can iterate over the entities regardless their current state.

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];
     }
}