Using Bevy: Creating a function (not system) that despawns all entities with a given component

Hey there, I've started making a game in Rust using Bevy. I'm trying to create a function that would essentially create a query for all entities with a Component type, passed as a parameter, and then recursively despawn all of those entities. Basically, it would be a generic cleanup function.

I've been Googling and I read that generic data types can help accomplish this, but I'm stuck on how to actually create the query, since this would not be a system, this would be a normal function that other systems can call.

This isn't necessary for my app, I'm just getting sort of tired of copying and pasting the same code. It would be nice to just call cleanup_components(), or something.

Any help is appreciated ^-^

Wait, by typing this I realized I could just pass the query as a parameter in the function calling it... Let me try that. If it works I'll leave this up in case anyone is looking for the same solution, but I think I figured it out on my own, lol

Okay, I got it working :3

My final solution was the method cleanup_state:

fn cleanup_state<T>(query: QueryIter<Entity, With<T>>, commands: &mut Commands) where T: Component {
    for item in query {

And in the code calling it, I created a system parameter called self_query that queried the components it needed to clean up. Then I just called it when necessary and passed self_query.iter().

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.