Cleanup of entities associated with states

(Michael Leandersson) #1


I made a small experiment with managed entities that is tied to a specific state with automatic cleanup when the state is stopped:

The idea is to use states to represent different levels and then remove all entities created specifically for a level when the levels state is stopped.

And since I am quite new to both ECS and gamedev I am wondering if there is an existing better pattern for handling this?

Thanks in advance :slight_smile:

1 Like
(Thomas Schaller) #2


If your state represents a whole level, why don’t you just delete all entities? Or, if it’s a subset you can just have a common parent and delete that.

In general, entities often have more complex requirements.

(Michael Leandersson) #3

Ah. Through the specs-hierarchy crate.

Thanks :slight_smile:

(Joël Lupien) #4

You can either use

  1. The Removal component and the exec_removal fn
  2. Put everything under a “top level” entity and delete it. Deleting the parent entity automatically deletes the child.

You are currently using a remakr of method one.

(Michael Leandersson) #5

I updated the destructor code to use the Removal component and the exec_removal fn.

However when executing the code i see that altough the components for the entities are removed, the entities themselves are not which leads to an ever growing number of entites while running the application. Am I missing something in my code or is this a bug?

(Khionu Sybiern) #6

The exec_removal function is supposed to delete the entities as well. If you are certain about the entities not being deleted, then that would be a bug. If you could create a minimal example of this bug, that would help us identify and fix the issue.

(Michael Leandersson) #7

There was no bug. One of the lines in my code created an entity without adding a Removal component… :pensive:

1 Like

Do you know if there is a way to delete all entities without having to track each entity then iterate them using entities.delete(entity)?

I know there doesn’t exist anything like entities.clear() but was looking for something similar.

(Taras Denysenko) #9

I believe world.delete_all() might be what you are looking for, as suggested in the Book.


Thanks @terrapass I should have been more specific tho.

I was looking to delete entities from within a system, essentially when my game switches to the next level it removes all entities from the previous level (pretty much everything).

Do you know of a way to clear all entities or all entities of a certain component type from within a system?

Or is just using the standard join loop then deleting them one at a time the likely solution?

Thanks for your help.