//! This example shows how you can know when a [`Component`] has been removed, so you can react to it.1//!2//! When a [`Component`] is removed from an [`Entity`], all [`Observer`] with an [`Remove`] trigger for3//! that [`Component`] will be notified. These observers will be called immediately after the4//! [`Component`] is removed. For more info on observers, see the5//! [observers example](https://github.com/bevyengine/bevy/blob/main/examples/ecs/observers.rs).6//!7//! Advanced users may also consider using a lifecycle hook8//! instead of an observer, as it incurs less overhead for a case like this.9//! See the [component hooks example](https://github.com/bevyengine/bevy/blob/main/examples/ecs/component_hooks.rs).10use bevy::prelude::*;1112fn main() {13App::new()14.add_plugins(DefaultPlugins)15.add_systems(Startup, setup)16// This system will remove a component after two seconds.17.add_systems(Update, remove_component)18// This observer will react to the removal of the component.19.add_observer(react_on_removal)20.run();21}2223/// This `struct` is just used for convenience in this example. This is the [`Component`] we'll be24/// giving to the `Entity` so we have a [`Component`] to remove in `remove_component()`.25#[derive(Component)]26struct MyComponent;2728fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {29commands.spawn(Camera2d);30commands.spawn((31Sprite::from_image(asset_server.load("branding/icon.png")),32// Add the `Component`.33MyComponent,34));35}3637fn remove_component(38time: Res<Time>,39mut commands: Commands,40query: Query<Entity, With<MyComponent>>,41) {42// After two seconds have passed the `Component` is removed.43if time.elapsed_secs() > 2.044&& let Some(entity) = query.iter().next()45{46commands.entity(entity).remove::<MyComponent>();47}48}4950fn react_on_removal(event: On<Remove, MyComponent>, mut query: Query<&mut Sprite>) {51// The `Remove` event was automatically triggered for the `Entity` that had its `MyComponent` removed.52let entity = event.entity();53if let Ok(mut sprite) = query.get_mut(entity) {54sprite.color = Color::srgb(0.5, 1., 1.);55}56}575859