I am trying to despawn some entitys I spawned using the commands.spawn() function but it is expecting a different type parament for the commands.entity().despawn function. Here is my code:
fn despawn(
commands: Commands,
player: Query<&Player>,
) {
commands.entity(player).despawn()
}
this code gives me the error: expected struct bevy::prelude::Entity
found struct bevy::prelude::Query<'_, '_, &Player>
How can I fix this?
Commands::entity
requires the Entity
, which is an unique identifier for an entity and associated components. To get the Entity
from a Query
, include it in the parameters like shown here:
player: Query<(Entity, &Player)>,
A Query
is an iterator-adjacent structure that yields the entities and components you're querying for. So your query can potentially yield multiple players if multiple entities have the Player
component. So you can handle multiple of them like so:
fn despawn(
mut commands: Commands,
players: Query<(Entity, &Player)>,
) {
for (player_id, _player) in players.iter() {
commands.entity(player_id).despawn();
}
}
Or if only one entity is expected, you can use get_single
:
if let Ok((player_id, _player)) = players.get_single() {
commands.entity(player_id).despawn();
}
Lastly, if you don't actually need to access the Player
component and have just included it to filter what entites are despawned, use a With
filter instead. See disjoint queries for an example. It would look like this:
fn despawn(
mut commands: Commands,
players: Query<Entity, With<Player>>,
) {
for player_id in players.iter() {
commands.entity(player_id).despawn();
}
}