From 09979cdb6500811bd5a8959a74e7aafcfd8c9c1d Mon Sep 17 00:00:00 2001 From: koe Date: Sat, 7 Sep 2024 16:47:05 -0500 Subject: [PATCH 1/4] add set_state extension method to Commands --- crates/bevy_state/src/commands.rs | 28 ++++++++++++++++++++++ crates/bevy_state/src/lib.rs | 4 ++++ examples/games/alien_cake_addict.rs | 10 +++----- examples/games/game_menu.rs | 37 +++++++++++------------------ 4 files changed, 49 insertions(+), 30 deletions(-) create mode 100644 crates/bevy_state/src/commands.rs diff --git a/crates/bevy_state/src/commands.rs b/crates/bevy_state/src/commands.rs new file mode 100644 index 0000000000000..38addffcff4f9 --- /dev/null +++ b/crates/bevy_state/src/commands.rs @@ -0,0 +1,28 @@ +use bevy_ecs::{system::Commands, world::World}; +use bevy_utils::tracing::debug; + +use crate::state::{FreelyMutableState, NextState}; + +/// Extension trait for [`Commands`](bevy_ecs::prelude::Commands) adding `bevy_state` helpers. +pub trait CommandsStatesExt { + /// Sets the next state the app should move to. + /// + /// Internally this schedules a command that updates the [`NextState`](crate::prelude::NextState) + /// resource with `state`. + /// + /// Note that commands introduce sync points to the ECS schedule, so modifying `NextState` + /// directly may be more efficient depending on your use-case. + fn set_state(&mut self, state: S); +} + +impl CommandsStatesExt for Commands<'_, '_> { + fn set_state(&mut self, state: S) { + self.add(move |w: &mut World| { + let mut next = w.resource_mut::>(); + if let NextState::Pending(prev) = &*next { + debug!("overwriting state {:?} with {:?}", prev, state); + } + next.set(state); + }); + } +} diff --git a/crates/bevy_state/src/lib.rs b/crates/bevy_state/src/lib.rs index b9ded18d4ef0e..5356560579460 100644 --- a/crates/bevy_state/src/lib.rs +++ b/crates/bevy_state/src/lib.rs @@ -34,6 +34,8 @@ #[cfg(feature = "bevy_app")] /// Provides [`App`](bevy_app::App) and [`SubApp`](bevy_app::SubApp) with state installation methods pub mod app; +/// Provides extension methods for [`Commands`](bevy_ecs::Commands). +pub mod commands; /// Provides definitions for the runtime conditions that interact with the state system pub mod condition; /// Provides definitions for the basic traits required by the state system @@ -53,6 +55,8 @@ pub mod prelude { #[doc(hidden)] pub use crate::app::AppExtStates; #[doc(hidden)] + pub use crate::commands::CommandsStatesExt; + #[doc(hidden)] pub use crate::condition::*; #[cfg(feature = "bevy_reflect")] #[doc(hidden)] diff --git a/examples/games/alien_cake_addict.rs b/examples/games/alien_cake_addict.rs index fa1b0543a9661..8c1941a3fb603 100644 --- a/examples/games/alien_cake_addict.rs +++ b/examples/games/alien_cake_addict.rs @@ -316,7 +316,6 @@ fn focus_camera( fn spawn_bonus( time: Res