Skip to content

Removing Observer panics the next time its event is triggered. #19673

Open
@gwafotapa

Description

@gwafotapa

Bevy version

0.16.1

The issue

Removing the Observer component without despawning the entity panics the next time its event is triggered.

use bevy::prelude::*;

#[test]
fn remove_observer_component() {
    #[derive(Event)]
    struct EventA;

    let mut world = World::new();
    let observer = Observer::new(|_: Trigger<EventA>| {});
    let mut entity_commands = world.spawn(observer);
    entity_commands.remove::<Observer>();
    world.trigger(EventA);
}

fn main() {}

If I'm correct, when an Observer is spawned, an ObserverState component is added to the entity as well. The world only unregisters an observer on the removing of ObserverState which does not happen in this case.

How can it be fixed?

I got around the issue by spawning the observer as a separate entity so I could despawn it and keep my original entity around. Maybe it could be fixed by adding an on_remove() hook to Observer but I'm not sure it's desirable as this is a rare scenario that you can get around easily. If it stays how it is however, it should be documented because it's natural when you realise that an observer is an entity like any other to insert or remove components.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ECSEntities, components, systems, and eventsC-BugAn unexpected or incorrect behaviorD-ModestA "normal" level of difficulty; suitable for simple features or challenging fixesS-Needs-InvestigationThis issue requires detective work to figure out what's going wrong

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions