Skip to content

Latest commit

 

History

History
73 lines (55 loc) · 2.51 KB

using_the_state_machine.md

File metadata and controls

73 lines (55 loc) · 2.51 KB

Using The State Machine

Bevy has a build-in state management that helps us to execute systems only in some states.

In the following example, we create the state machine containing only one state. When the system is in this state (which is always true in the example), it prints In MainState.

First, we create a enum MyStates that derives States.

#[derive(States, Default, Debug, Clone, Eq, PartialEq, Hash)]
enum MyStates {
    #[default]
    MainState,
}

The enum MyStates also derives Default, Debug, Clone, Eq, PartialEq and Hash, as required by the underlying system. Additionally, we mark MainState as the default state by #[default].

Then we add MyStates to our App.

App::new().add_state::<MyStates>().add_systems(Update, print.run_if(in_state(MyStates::MainState)))

We use the method add_state of App to add the states. It will be initialized to the default state. For the system print, we turn it on when the system is in the state MyStates::MainState. We use the function in_state to check if it is the specified state.

The full code is as follows:

use bevy::{
    app::{App, Update},
    ecs::schedule::{common_conditions::in_state, IntoSystemConfigs, States},
    DefaultPlugins,
};

#[derive(States, Default, Debug, Clone, Eq, PartialEq, Hash)]
enum MyStates {
    #[default]
    MainState,
}

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_state::<MyStates>()
        .add_systems(Update, print.run_if(in_state(MyStates::MainState)))
        .run();
}

fn print() {
    println!("In MainState");
}

Output:

In MainState
In MainState
In MainState
... (repeat infinitely)

In the next tutorial, we will show how to manipulate states.

➡️ Next: Changing States

📘 Back: Table of contents