Skip to main content

resource_exists_and

Function resource_exists_and 

Source
pub fn resource_exists_and<T>(
    condition: impl Fn(&T) -> bool,
) -> impl FnMut(Option<Res<'_, T>>)
where T: Resource,
Expand description

Generates a SystemCondition-satisfying closure that returns true if the resource exists and satisfies a closure.

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

§Example

schedule.add_systems(
    // `resource_exists_and` will only return true
    // if the given resource exists and satisfies the given condition
    increment.run_if(resource_exists_and(|should_run: &ShouldRun| should_run.0.is_ascii())),
);

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

world.insert_resource(Counter(0));

// `ShouldRun` hasn't been added, so `increment` can't run
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0, 0);
world.insert_resource(ShouldRun(String::from("bevy")));

// `ShouldRun` exists and satisfies the run conditions, so `increment` can run
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0, 1);
world.get_resource_mut::<ShouldRun>().unwrap().0 = String::from("bevy ❤");

// `ShouldRun` exists but has non-ASCII characters and thus
// does not satisfy the run conditions, so `increment` won't run
schedule.run(&mut world);
assert_eq!(world.resource::<Counter>().0, 1);