States
Model menus, levels and pause screens as states, run systems on entering and leaving them, gate systems with in_state, and use sub-states and computed states.
On this page
A state is an app-wide value, usually an enum, that says what mode the game is in: the main menu, loading, playing, paused, game over. Systems can run when a state is entered or left, and only while it holds. States keep each mode's setup, logic and cleanup in one place.
Define and add a state#
use neo::prelude::*;
#[derive(States, Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
enum GameState {
#[default]
Menu,
Playing,
GameOver,
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_state::<GameState>() // starts in the Default: Menu
.add_systems(OnEnter(GameState::Menu), spawn_menu)
.add_systems(OnExit(GameState::Menu), despawn_menu)
.add_systems(OnEnter(GameState::Playing), spawn_level)
.add_systems(Update, (move_player, spawn_enemies).run_if(in_state(GameState::Playing)))
.run();
}init_state::<S>() starts in S::default(); insert_state(value) starts in a value you choose. States need DefaultPlugins (or the StatesPlugin) to be added first.
Change state#
Set the next state with NextState<S>. The change applies in the StateTransition schedule, which runs once per frame after PreUpdate.
fn start_game(keys: Res<ButtonInput<KeyCode>>, mut next: ResMut<NextState<GameState>>) {
if keys.just_pressed(KeyCode::Enter) {
next.set(GameState::Playing);
}
}
fn show_state(state: Res<State<GameState>>) {
info!("now in {:?}", state.get());
}| API | What it does |
|---|---|
Res<State<S>> | The current state: state.get(), or compare with *state == GameState::Playing. |
ResMut<NextState<S>> | set(value) queues a change. Setting the current state again runs OnExit and OnEnter again. |
next.set_if_different(value) | Queues a change only if it's a different state. |
next.reset() | Cancels a queued change. |
commands.set_state(value), commands.set_state_if_different(value) | The same through commands. |
MessageReader<StateTransitionEvent<S>> | Every transition, with exited and entered. |
Only the last value set before StateTransition runs counts.
Transition schedules#
| Schedule | Runs |
|---|---|
OnExit(state) | When leaving state. |
OnTransition { exited, entered } | When going from exactly exited to exactly entered, after OnExit and before OnEnter. |
OnEnter(state) | When entering state, including the initial state at startup, which runs before PreStartup. |
Gate systems on a state#
| Run condition | True when |
|---|---|
in_state(value) | The state is value. |
state_exists::<S> | State<S> exists (useful for sub-states and computed states). |
state_changed::<S> | The state changed this frame. |
Put many systems behind one check by gating a set:
app.configure_sets(Update, GameplaySet.run_if(in_state(GameState::Playing)));Clean up with state-scoped entities#
Entities with DespawnOnExit(state) are despawned when that state is left; DespawnOnEnter(state) when it is entered. This replaces most hand-written cleanup systems.
fn spawn_menu(mut commands: Commands) {
commands.spawn((
Text::new("Press Enter to play"),
DespawnOnExit(GameState::Menu),
));
}| Component | Effect |
|---|---|
DespawnOnExit(state), DespawnOnEnter(state) | Despawns the entity and its children. |
DisableOnExit(state), DisableOnEnter(state) | Inserts Disabled instead, keeping the entity for later. |
EnableOnExit(state), EnableOnEnter(state) | Removes Disabled. |
Sub-states#
A sub-state only exists while its source state has a given value. Pausing is a typical one: it means nothing in the menu.
#[derive(SubStates, Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[source(GameState = GameState::Playing)]
enum Pause {
#[default]
Running,
Paused,
}
app.add_sub_state::<Pause>()
.add_systems(Update, move_player.run_if(in_state(Pause::Running)))
.add_systems(OnEnter(Pause::Paused), show_pause_menu);When GameState becomes Playing, State<Pause> is created with its default; when GameState leaves Playing, it's removed. You set a sub-state with NextState<Pause> like any state.
Computed states#
A computed state is calculated from other states and can't be set directly. Use one to name a condition that spans several states:
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct InLevel;
impl ComputedStates for InLevel {
type SourceStates = GameState;
fn compute(source: GameState) -> Option<Self> {
match source {
GameState::Playing | GameState::GameOver => Some(InLevel),
GameState::Menu => None,
}
}
}
app.add_computed_state::<InLevel>()
.add_systems(OnEnter(InLevel), spawn_level)
.add_systems(OnExit(InLevel), despawn_level);SourceStates can be a tuple of states, and any of them can be wrapped in Option to also run when that state doesn't exist. Set const ALLOW_SAME_STATE_TRANSITIONS: bool = false; in the impl to skip OnEnter and OnExit when the computed value stays the same while its sources change.
Examples#
Run these from the engine core's workspace:
| Example | What it shows |
|---|---|
cargo run --example states | A menu and a game as two states. |
cargo run --example sub_states --features neo_dev_tools | A pause sub-state that only exists in game. |
cargo run --example computed_states --features neo_dev_tools | Computed states for in-game, paused, turbo and tutorial modes. |
cargo run --example custom_transitions --features neo_dev_tools | Your own transition schedules, such as re-entering the same state. |
cargo run --example state_scoped | DespawnOnExit and DespawnOnEnter. |
The --features neo_dev_tools examples log transitions with a developer tool that isn't part of NEO's default builds; the state API itself needs no extra feature.