Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions crates/bevy_state/src/state_scoped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ where

/// Despawns entities marked with [`DespawnOnExit<S>`] when their state no
/// longer matches the world state.
/// If the entity has already been despawned no warning will be emitted
pub fn despawn_entities_on_exit_state<S: States>(
mut commands: Commands,
mut transitions: MessageReader<StateTransitionEvent<S>>,
Expand All @@ -86,7 +87,7 @@ pub fn despawn_entities_on_exit_state<S: States>(
};
for (entity, binding) in &query {
if binding.0 == *exited {
commands.entity(entity).despawn();
commands.entity(entity).try_despawn();
}
}
}
Expand Down Expand Up @@ -133,6 +134,7 @@ pub struct DespawnOnEnter<S: States>(pub S);

/// Despawns entities marked with [`DespawnOnEnter<S>`] when their state
/// matches the world state.
/// If the entity has already been despawned no warning will be emitted
pub fn despawn_entities_on_enter_state<S: States>(
mut commands: Commands,
mut transitions: MessageReader<StateTransitionEvent<S>>,
Expand All @@ -152,7 +154,7 @@ pub fn despawn_entities_on_enter_state<S: States>(
};
for (entity, binding) in &query {
if binding.0 == *entered {
commands.entity(entity).despawn();
commands.entity(entity).try_despawn();
}
}
}
10 changes: 10 additions & 0 deletions examples/ecs/state_scoped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
//!
//! This pattern is useful for managing menus, levels, or other state-specific
//! content that should only exist during certain states.
//!
//! If the entity was already despawned then no error will be logged
//! This means that you don't have to worry about duplicating in a hierachy

use bevy::prelude::*;

Expand Down Expand Up @@ -46,6 +49,7 @@ fn on_a_enter(mut commands: Commands) {
left: px(0),
..default()
},
(children![DespawnOnExit(GameState::A)]),
));
}

Expand All @@ -65,6 +69,10 @@ fn on_a_exit(mut commands: Commands) {
left: px(500),
..default()
},
// You can apply this even when the parent has a state scope
// It is unneccesary but in complex hierarchies
// it saves you from having to mentally track which components are found at the top level
(children![DespawnOnEnter(GameState::A)]),
));
}

Expand All @@ -84,6 +92,7 @@ fn on_b_enter(mut commands: Commands) {
left: px(0),
..default()
},
(children![DespawnOnExit(GameState::B)]),
));
}

Expand All @@ -103,6 +112,7 @@ fn on_b_exit(mut commands: Commands) {
left: px(500),
..default()
},
(children![DespawnOnEnter(GameState::B)]),
));
}

Expand Down
Loading