bevy icon indicating copy to clipboard operation
bevy copied to clipboard

Support .run_if() on observers

Open forbjok opened this issue 1 year ago • 4 comments

What problem does this solve or what need does it fill?

Just like with systems, sometimes observers are only relevant for a specific state. It would be much more convenient to be able to do this on observers using .run_if() or something similar, than having to manually check the state in the function code.

What solution would you like?

To be able to use .run_if() on observers to limit when they will run, just like on regular systems.

forbjok avatar Jul 06 '24 21:07 forbjok

Just forwarding my thoughts from discord

On run conditions for observers specifically they don't make sense & add a lot of complexity. This came up before in #ecs-dev. Run conditions are for things in schedules. IMO this is a problem with how bevys systems are designed. They always run regardless of if their params match. In flecs what determines if an observer runs is the observers query (queries in flecs aren't limited to iterating entities & matching overlapping archetypes). Like right now if a system asks for Res<Foo> where Foo doesn't exist it panics. If the behavior was instead that the system doesn't run then observers checking for state would just be InState<Menu>. Bevy's type system limitations are also showing here because doing this requires more const generics which would be too limiting anyway cause it would have zero dynamic capabilities.

iiYese avatar Jul 06 '24 22:07 iiYese

Like right now if a system asks for Res<Foo> where Foo doesn't exist it panics.

This is one thing that makes the lack of support for run conditions on observers even more annoying. I just ran into this as well, where when I added the manual state check to the observer function, triggering it would cause a crash because a resource that would only exist in the specific state that observer was relevant in, correctly and as expected did not exist. To work around that I also had to wrap it in an option and use a let-else statement to unwrap it or return.

forbjok avatar Jul 06 '24 23:07 forbjok

My take:

Run conditions are good for composition. You write a run condition once and then you can apply it to whatever system you want. But not to observers atm.

So you couldn't use a run condition like in_state(Foo), you'd have to add Res<State<Foo>> as an argument to your observer and check in there. For more complex run conditions, especially run conditions provided by 3rd-party libraries, this can become very annoying.

I suspect that end-users of observers will keep meeting the lack of run condition support with disappointment.

benfrankel avatar Jul 08 '24 04:07 benfrankel

I do think that systems not running if one of their required resources doesn't exist would be a good thing btw, I've brought it up before: https://github.com/bevyengine/bevy/issues/12660#issuecomment-2016641765.

benfrankel avatar Jul 08 '24 04:07 benfrankel

Just want to throw my hat into this and say that I also think this should be a thing. I just ran into a use case where this would be super helpful, cus now i have to add in the manual checks inside a bunch of Observers and im not looking forward to it.

Peepo-Juice avatar Jan 01 '25 23:01 Peepo-Juice

The simplest usecase - subscribers to an event that is supposed to be handled only on one screen but they still need screen check. Not horrible, but certainly annoying. Maybe we can add some ignore attribute so that Event derive can be ignored in some states?

olekspickle avatar May 25 '25 18:05 olekspickle

Here's a workaround for state scoped observers

macro_rules! scoped_observer {
    ($state:ident::$scope:ident, $id: ident, $fn: ident) => {
        #[derive(Component)]
        #[require(
            Name::new(stringify!($id)),
            Observer::new($fn),
            StateScoped::<$state>($state::$scope),
        )]
        struct $id;
    }
}

Use it like this:

pub fn plugin(app: &mut App) {
    app.add_systems(OnEnter(MainStates::Gameplay), enter_gameplay_system);
}

fn enter_gameplay_system(
    mut commands: Commands,
) {
    scoped_observer!(MainStates::Gameplay, AnyNameForMyObserver, my_observer);
    commands.spawn(AnyNameForMyObserver);
}

fn my_observer(...) { ... }

You can even call scoped_observer! multiple times with different identifiers for different states.

As a bonus, these observers will now be named in any inspector view.

BrainBacon avatar Aug 22 '25 12:08 BrainBacon

Here's a newer version of my macro that uses the paste crate to avoid the need to manually make an identifier:

use paste::paste;

macro_rules! scoped {
    ($state:ident::$scope:ident, $fn: ident) => {
        paste! {
            {
                #[derive(Component)]
                #[require(
                    Observer::new($fn),
                    Name::new(stringify!([< $scope Scoped $fn:camel >]))
                    StateScoped::<$state>($state::$scope),
                )]
                struct [< $scope Scoped $fn:camel >];

                [< $scope Scoped $fn:camel >]
            }
        }
    }
}

Usage is a bit simpler:

pub fn plugin(app: &mut App) {
    app.add_systems(OnEnter(MainStates::Gameplay), enter_gameplay_system);
}

fn enter_gameplay_system(
    mut commands: Commands,
) {
    commands.spawn(scoped!(MainStates::Gameplay, my_observer));
}

fn my_observer(...) { ... }

BrainBacon avatar Sep 07 '25 11:09 BrainBacon