Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
11 changes: 11 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2007,6 +2007,17 @@ description = "Demonstrates how to send and receive events of the same type in a
category = "ECS (Entity Component System)"
wasm = false

[[example]]
name = "entity_disabling"
path = "examples/ecs/entity_disabling.rs"
doc-scrape-examples = true

[package.metadata.example.entity_disabling]
name = "Entity disabling"
description = "Demonstrates how to hide entities from the ECS without deleting them"
category = "ECS (Entity Component System)"
wasm = true

[[example]]
name = "fixed_timestep"
path = "examples/ecs/fixed_timestep.rs"
Expand Down
155 changes: 155 additions & 0 deletions examples/ecs/entity_disabling.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
//! Disabling entities is a powerful feature that allows you to hide entities from the ECS without deleting them.
Comment thread
alice-i-cecile marked this conversation as resolved.
Outdated
//!
//! This can be useful for implementing features like "sleeping" objects that are offscreen
//! or managing networked entities.
//!
//! Note that you should *not* use this feature to simply make entities invisible!
Comment thread
alice-i-cecile marked this conversation as resolved.
Outdated
//! [`Visibility`](bevy::prelude::Visibility) should be used for that:
//! disabled entities are skipped entirely, which can lead to subtle bugs.
//!
//! # Default query filters
//!
//! Under the hood, Bevy uses a "default query filter" that skips entities with the
//! the [`Disabled`] component.
//! These filters act as a by-default exclusion list for all queries,
//! and can be bypassed by explicitly including these components in your queries.
Comment thread
alice-i-cecile marked this conversation as resolved.

use bevy::ecs::entity_disabling::Disabled;
use bevy::prelude::*;

fn main() {
App::new()
.add_plugins((DefaultPlugins, MeshPickingPlugin))
.add_observer(disable_entities_on_click)
.add_systems(
Update,
(list_all_named_entities, reenable_entities_on_space),
)
.add_systems(Startup, (setup_scene, display_instructions))
.run();
}

fn disable_entities_on_click(
trigger: Trigger<Pointer<Click>>,
ignored_query: Query<(), Or<(With<Window>, With<Text>)>>,

@Carter0 Carter0 Feb 7, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This query is super fascinating to me cause you are querying for 'Void' with some stuff on it. I know that's not the point of this example, but what's the difference between this and just querying for all entities with those components and then doing an equality check on the entities below?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will avoid actually fetching / locking the data :) We don't actually care about the data contained inside!

mut commands: Commands,
) {
let clicked_entity = trigger.target();
// Windows and text are entities and can be clicked!
// We definitely don't want to disable the window itself,
// because that would cause the app to close!
if ignored_query.contains(clicked_entity) {
return;
}
Comment thread
alice-i-cecile marked this conversation as resolved.

// Just add the `Disabled` component to the entity to disable it.
// Note that the `Disabled` component is *only* added to the entity,
// its children are not affected.
commands.entity(clicked_entity).insert(Disabled);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's interesting! Since the entity is disabled, does that cause the parent/child relationship to break, orphaning those children? Or does the relationship stick around and the children just have a disabled parent?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The latter :) I don't think much of our code is robust to it yet though!

}

#[derive(Component)]
struct EntityNameText;

// The query here will not find entities with the `Disabled` component,
// because it does not explicitly include it.
fn list_all_named_entities(
query: Query<&Name>,
mut name_text_query: Query<&mut Text, With<EntityNameText>>,
mut commands: Commands,
) {
let mut text_string = String::from("Named entities found:\n");
// Query iteration order is not guaranteed, so we sort the names
Comment thread
alice-i-cecile marked this conversation as resolved.
// to ensure the output is consistent.
let mut names: Vec<Name> = query.iter().cloned().collect();
Comment thread
alice-i-cecile marked this conversation as resolved.
Outdated
names.sort_by_key(|name| name.clone());

for name in names.iter() {
text_string.push_str(&format!("{:?}\n", name));
}
Comment thread
alice-i-cecile marked this conversation as resolved.
Outdated

if let Ok(mut text) = name_text_query.get_single_mut() {
*text = Text::new(text_string);
} else {
commands.spawn((
EntityNameText,
Text::new(
"Click an entity to disable it.
\nPress Space to re-enable all disabled entities.",
),
Comment thread
alice-i-cecile marked this conversation as resolved.
Outdated
Node {
position_type: PositionType::Absolute,
top: Val::Px(12.0),
right: Val::Px(12.0),
..default()
},
));
}
}

fn reenable_entities_on_space(
mut commands: Commands,
// This query can find disabled entities,
// because it explicitly includes the `Disabled` component.
disabled_entities: Query<Entity, With<Disabled>>,
input: Res<ButtonInput<KeyCode>>,
) {
if input.just_pressed(KeyCode::Space) {
for entity in disabled_entities.iter() {
// To re-enable an entity, just remove the `Disabled` component.
commands.entity(entity).remove::<Disabled>();
}
}
}

const X_EXTENT: f32 = 900.;

fn setup_scene(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
commands.spawn(Camera2d::default());

let named_shapes = [
(Name::new("Annulus"), meshes.add(Annulus::new(25.0, 50.0))),
(
Name::new("Bestagon"),
meshes.add(RegularPolygon::new(50.0, 6)),
),
(Name::new("Rhombus"), meshes.add(Rhombus::new(75.0, 100.0))),
];
let num_shapes = named_shapes.len();

for (i, (name, shape)) in named_shapes.into_iter().enumerate() {
// Distribute colors evenly across the rainbow.
let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7);

commands.spawn((
name,
Mesh2d(shape),
MeshMaterial2d(materials.add(color)),
Transform::from_xyz(
// Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2.
-X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
0.0,
0.0,
),
));
}
}

fn display_instructions(mut commands: Commands) {
commands.spawn((
Text::new(
"Click an entity to disable it.
\nPress Space to re-enable all disabled entities.",
Comment thread
alice-i-cecile marked this conversation as resolved.
Outdated
),
Node {
position_type: PositionType::Absolute,
top: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
));
}