Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 6 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,8 @@ 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 +88,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 +135,8 @@ 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 +156,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();
}
}
}
11 changes: 11 additions & 0 deletions examples/ecs/state_scoped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
//!
//! 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 duplicate [`DespawnOnExit`] and
//! [`DespawnOnEnter`] components deep in your hierarchy.

use bevy::prelude::*;

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

Expand All @@ -65,6 +70,10 @@ fn on_a_exit(mut commands: Commands) {
left: px(500),
..default()
},
// You can apply this even when the parent has a state scoped component.
// It is unnecessary 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 +93,7 @@ fn on_b_enter(mut commands: Commands) {
left: px(0),
..default()
},
(children![DespawnOnExit(GameState::B)]),
));
}

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

Expand Down