Skip to content

State change taking place after its stage #4308

Closed
@lukors

Description

@lukors

Bevy version

0.6.1

Operating system & version

Ubuntu 20.04.3 LTS

What you did

  • An exclusive system adds Res<MyResource> at the start of CoreStage::Update, and then an exclusive system removes it at the end of the stage.
  • input_system changes MyState to MyState::Two when you click the left mouse button.
  • using_system runs in CoreStage::Update when MyState::Two is entered, and has Res<MyResource> as an argument.

Run the following code and left click.

use bevy::prelude::*;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_state_to_stage(CoreStage::Update, MyState::One)
        .add_system_set_to_stage(
            CoreStage::Update,
            SystemSet::new()
                .with_system(inserting_system.exclusive_system().at_start())
                .with_system(removing_system.exclusive_system().at_end())
                .with_system(input_system)
                .with_system(using_system.with_run_criteria(State::on_enter(MyState::Two))),
        )
        .run();
}

#[derive(Clone, Eq, PartialEq, Debug, Hash)]
enum MyState {
    One,
    Two,
}

struct MyResource;

fn inserting_system(world: &mut World) {
    world.insert_resource(MyResource);
}

fn removing_system(world: &mut World) {
    world.remove_resource::<MyResource>();
}

fn input_system(i_mouse_button: Res<Input<MouseButton>>, mut my_state: ResMut<State<MyState>>) {
    if i_mouse_button.just_pressed(MouseButton::Left) {
        my_state.set(MyState::Two);
    }
}

fn using_system(_my_resource: Res<MyResource>) {}

What you expected to happen

No crash, because the exclusive system that removes the Res<MyResource> is set to run at the end of the stage, which should be after state transitions.

What actually happened

Crash because it can't find the Res<MyResource>.

More info

Workaround: Insert it at the beginning of the next stage instead of at the end of this one.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ECSEntities, components, systems, and eventsC-BugAn unexpected or incorrect behavior

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions