Hello everyone,
I am currently in the middle of creating my c++ game engine and I want to ask how do I implement entity references in a clean way. When I say “entity reference” I mean some form of handle that allows me to get a specific entity(with a unique ID) within an array.
In my engine I have a big fixed array of entities(an entity is just a struct) and a counter:
struct Entity
{
uint32_t id;
// other data
};
Entity entities[100];
uint32_t entityCount;
// iteration
for(int32_t i = 0; i < entityCount; ++i)
{
Entity* entity = &entities[i];
// do stuff
}
When I want to add an entity to the list i just use the entityCount as new index and increment it:
Entity* createdEntity = &entities[entityCount++];
When I want to remove an entitity from the list i move the last entity into the slot i want to delete:
uint32_t entityIndexToRemove = 1;
entities[entityIndexToRemove] = entities[--entityCount];
In this way I can keep the entities contigous in memory.
Since some entities get moved in the array when removing entities i need a way to get an entity based on the unique id. I am looking for a clean and fast way to create these references without having to look in the entire array to find the unique id.
Thanks.