How to remove/delete/drop a component across all entities

4.6k Views Asked by At

As part of setup, I'll be generating a component that will then be used to finish the setup of other components. That component will no longer be needed, after that point. So, is there a way of deleting an entire component all at once? I've found a way to delete the components of each entity, but wouldn't that be drastically less efficient?

Until I know how to do that, I'll just be doing the setup over a bunch of bundles. This will be unable to benefit from the ECS system. If I had a loading screen, it would be that much longer for it.

2

There are 2 best solutions below

1
On
commands.entity(entity).remove::<Component>()
0
On

You could try removing the component all together by making an exclusive system that gets the world's components and storages and try to remove the stuff corresponding to your component. However, this entails transmuting &Components to &mut Components (unless there is some other way to get the mutable Components field in World), which is UB. This is a very bad idea and should not be done, but is possible.

Personally, I think you are doing something wrong by making a type that only exists for a moment. I could be wrong about your use case (it would have been nice if you provided it), but something like a resource can be removed easily via commands.remove_resource, in which you can store a table of entities and their associated value. Maybe this won't work, but I'm sure there is an alternative.

Here is the appropriate way to remove all components (just for reference):

fn delete_components(mut commands: Commands, query: Query<Entity, With<YourComponent>> {
  { // put your condition here
    // or if the component is not needed after a stage in startup,
    // you could make this system a startup system after that stage
    for entity in query.iter() {
      commands.entity(entity).remove::<YourComponent>();
    }
  }
}