pub fn resource_exists_and_changed<T>(res: Option<Res<'_, T>>) -> bool
where T: Resource,
Expand description

A Condition-satisfying system that returns true if the resource of the given type has had its value changed since the condition was last checked.

The value is considered changed when it is added. The first time this condition is checked after the resource was added, it will return true. Change detection behaves like this everywhere in Bevy.

This run condition does not detect when the resource is removed.

The condition will return false if the resource does not exist.

§Example

app.add_systems(
    // `resource_exists_and_changed` will only return true if the
    // given resource exists and was just changed (or added)
    my_system.run_if(
        resource_exists_and_changed::<Counter>
        // By default detecting changes will also trigger if the resource was
        // just added, this won't work with my example so I will add a second
        // condition to make sure the resource wasn't just added
        .and_then(not(resource_added::<Counter>))
    ),
);

fn my_system(mut counter: ResMut<Counter>) {
    counter.0 += 1;
}

// `Counter` doesn't exist so `my_system` won't run
app.run(&mut world);
world.init_resource::<Counter>();

// `Counter` hasn't been changed so `my_system` won't run
app.run(&mut world);
assert_eq!(world.resource::<Counter>().0, 0);

world.resource_mut::<Counter>().0 = 50;

// `Counter` was just changed so `my_system` will run
app.run(&mut world);
assert_eq!(world.resource::<Counter>().0, 51);