Search code examples
rustbevy

How to modify a component in Bevy when using get_single()?


I am making a simple top-down "bullet hell" game with Bevy. I've tried to create a system that takes care of the player's dashing like this:

fn player_dashing_system(
    kb: Res<Input<KeyCode>>,
    query: Query<&mut Player>
) {
    if let Ok(&mut player) = query.get_single() {
        if kb.just_pressed(KeyCode::Space) {
            player.speed = BASE_PLAYER_DASH_SPEED;
        }
    }
}

but I get this error:

error[E0308]: mismatched types
--> src\player.rs:108:15
    |
108 |     if let Ok(&mut Player) = query.get_single() {
    |               ^^^^^^^^^^^    ------------------ this expression has type `Result<&Player, QuerySingleError>`
    |               |
    |               types differ in mutability
    |               help: you can probably remove the explicit borrow: `Player`
    |
    = note:      expected reference `&Player`
            found mutable reference `&mut _`

I have tried fiddling around with the mutability of the variables but couldn't get anything to work.


Solution

  • Use get_single_mut.

    Also remove the &mut from Ok(&mut player), otherwise the pattern will dereference the player, which is likely not what you want.