Advertisement

How to handle entity removal/creation while world iteration

Started by June 07, 2022 08:32 PM
3 comments, last by teempade04 1 year, 9 months ago

Is it possible to create/remove entities while iterating over them? Is it possible to create an “entity_iterator” structure that handles this process? For example:

struct world {
	entity entities[100];
	uint32_t entity_count;
};

for(entity_iterator iterator = iterate_entities(world); is_valid(&iterator); next(&iterator) {
	entity* e = iterator.current_entity;
	if(e->value == 1) {
		entity* newe = add_entity(world);
		// initialize new entity here
	} else {
		delete_entity(world, e);
	}
}

If this is not possible how do game engines handle entity creation/removal? Do they have some sort of queues?

This is how i create/remove entities:

Entity* created_entity = &entities[entity_count++];
uint32_t entity_index_to_remove = 1;
entities[entity_index_to_remove = entities[--entity_count];

Thanks

It can be however you want to build it.

You must be extremely careful about modifying containers while iterating over them. Details vary by the container you're using. Some operations invalidate all iterators, some invalidate iterators pointing to a specific object, some have other requirements.

In large engines there is often a delayed / deferred process. While the game is running simulation you make a call to destroy the object. The call immediately sets a flag on the object but the actual removal and destruction are delayed until a more suitable time. Objects might be removed from the world but still exist in memory as dead items, they might get moved around in a pool of objects for eventual reuse/recycling, they might get completely cleaned up and deallocated, but all that work takes place at a later time rather than in the middle of the simulation work.

Advertisement

May I suggest an approach where you don't remove the entity while you're in your “update” loop.

Instead just add a flag that the entity is killed. Let this flag stay active on the next loop around the game main loop so that every subsystem can react to the entity being killed. Then at the end of this loop after your game updates have run you actually delete the object.

Never delete while iterating. You're going to blow your foot off.

Within the persistence context, the entity instances and their lifecycle are managed. The EntityManager API is used to create and remove persistent entity

myfiosgateway.one

mobdro

This topic is closed to new replies.

Advertisement