3 ms·
I use a system much like this for entity management for games, but with an additional property that I don't see outlined here: when an entity is "despawned" (d
by adamrezich 3y ago
I use a system much like this for entity management for games, but with an additional property that I don't see outlined here:
when an entity is "despawned" (destroyed), it is not "freed" immediately. instead, its id ("generation counter" in the article) is set to 0 (indicating it is invalid, as the first valid id is 1), and it's added to a list of entities that were despawned this frame. my get-pointer-from-handle function returns both a pointer, and a "gone" bool, which is true if the entity the handle points to has an id of 0 (indicating it used to exist but has since been despawned), or if the id in the handle and the id in the pointed-to entity don't match (indicating that the entity the handle pointed at was despawned, and something else was spawned in its place in memory). then, at the end of each frame, the system goes through the list of despawning entities, and it's there that the memory is reclaimed to be reused by newly-spawned entities.
in this system, it's up to the user of the get-pointer-from-handle function to check "if gone", and handle things accordingly. it's a bit cumbersome to have to do this check everywhere that you want to get a pointer to an entity, but with some discipline, you'll never encounter "use-after-free" situations, or game logic errors caused by assuming something that existed last frame is still there when it might be gone now for any number of reasons—because you're explicitly writing what fallback behavior should occur in such a situation.