⚠️ Beta State

PyBevy is in an early and experimental stage. The API is incomplete, subject to breaking changes without notice, and you should expect bugs. Many features are still under development.

Removal Detection

Detect when components are removed from entities using observers.

Introduction

Sometimes you need to react when a component is removed from an entity. PyBevy's observer system, powered by Bevy's ECS, lets you register callbacks that trigger on component removal events.

from pybevy.prelude import *

Components

@component
class Shield(Component):
    value: float = 50.0

Setup

Spawn an entity with a Shield component that will be removed after a delay.

def setup(commands: Commands) -> None:
    commands.spawn(Shield(value=50.0))
    print("Entity spawned with Shield")

Removal System

After 2 seconds, remove the Shield component to trigger the removal detection.

_elapsed = [0.0]
 
 
def remove_after_delay(time: Res[Time], query: Query[Entity, With[Shield]], commands: Commands) -> None:
    _elapsed[0] += time.delta_secs()
    if _elapsed[0] > 2.0:
        for entity in query:
            commands.entity(entity).remove(Shield)
            print("Shield removed!")
        _elapsed[0] = -999.0  # Only trigger once

Running the App

@entrypoint
def main(app: App) -> App:
    return (
        app
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, remove_after_delay)
    )
 
if __name__ == "__main__":
    main().run()

Running this example

Use PyBevy's hot reload feature to run and develop this example. If you don't have PyBevy installed, check out the Quick Start guide.

$pybevy watch removal_detection.py

The code will reload automatically when you make changes to the file.


From Python to Rust

Notice how the core concepts in the code—Commands, Assets, App, and Systems—are identical to the original Bevy example?

This is the power of pybevy! It lets you learn Bevy's powerful, data-driven architecture in friendly Python.

When your project grows and you're ready for maximum, native performance, you'll already know the concepts to start writing systems in Bevy Engine with Rust.