Path: blob/main/crates/bevy_state/src/state/freely_mutable_state.rs
6596 views
use bevy_ecs::{1event::EventWriter,2prelude::Schedule,3schedule::IntoScheduleConfigs,4system::{Commands, IntoSystem, ResMut},5};67use super::{states::States, take_next_state, transitions::*, NextState, State};89/// This trait allows a state to be mutated directly using the [`NextState<S>`](crate::state::NextState) resource.10///11/// While ordinary states are freely mutable (and implement this trait as part of their derive macro),12/// computed states are not: instead, they can *only* change when the states that drive them do.13#[diagnostic::on_unimplemented(note = "consider annotating `{Self}` with `#[derive(States)]`")]14pub trait FreelyMutableState: States {15/// This function registers all the necessary systems to apply state changes and run transition schedules16fn register_state(schedule: &mut Schedule) {17schedule.configure_sets((18ApplyStateTransition::<Self>::default()19.in_set(StateTransitionSystems::DependentTransitions),20ExitSchedules::<Self>::default().in_set(StateTransitionSystems::ExitSchedules),21TransitionSchedules::<Self>::default()22.in_set(StateTransitionSystems::TransitionSchedules),23EnterSchedules::<Self>::default().in_set(StateTransitionSystems::EnterSchedules),24));2526schedule27.add_systems(28apply_state_transition::<Self>.in_set(ApplyStateTransition::<Self>::default()),29)30.add_systems(31last_transition::<Self>32.pipe(run_exit::<Self>)33.in_set(ExitSchedules::<Self>::default()),34)35.add_systems(36last_transition::<Self>37.pipe(run_transition::<Self>)38.in_set(TransitionSchedules::<Self>::default()),39)40.add_systems(41last_transition::<Self>42.pipe(run_enter::<Self>)43.in_set(EnterSchedules::<Self>::default()),44);45}46}4748fn apply_state_transition<S: FreelyMutableState>(49event: EventWriter<StateTransitionEvent<S>>,50commands: Commands,51current_state: Option<ResMut<State<S>>>,52next_state: Option<ResMut<NextState<S>>>,53) {54let Some(next_state) = take_next_state(next_state) else {55return;56};57let Some(current_state) = current_state else {58return;59};60internal_apply_state_transition(event, commands, Some(current_state), Some(next_state));61}626364