Type Alias bevy_query_ext::OrDefault

source ·
pub type OrDefault<T> = ModQ<OrDefaultQ<T>>;
Expand description

If the query exists on the entity it is returned, or else the default for the query result

§Example

#[derive(Component, Clone, Copy, Default)]
struct Velocity2D{x: f32, y: f32};

// Note: This query is also aliased as `CopiedOrDefault`
fn example(query: Query<OrDefault<Copied<Velocity2D>>>) {
    // If item does not have Velocity2D, a default is created
    let _: Velocity2D = query.get_single().unwrap();
}

§Counter example: Can’t use on component directly

#[derive(Component, Clone, Copy, Default)]
struct Velocity2D{x: f32, y: f32};

fn bad_example(query: Query<OrDefault<Velocity2D>>) {
    let _: Velocity2D = query.get_single().unwrap();
}

§Example: Default for references

Normally default is not implemented for &T, even if T: Default. The following will not work

#[derive(Component, Copy, Clone, Default)]
struct Velocity2D{x: f32, y: f32};

fn example(query: Query<OrDefault<&Velocity2D>>) {
    let _: &Velocity2D = query.get_single().unwrap();
}

But you can implement it manually if you don’t want to copy/clone components but still have a default. You’ll have to try something like this though:

#[derive(Component)]
struct Velocity2D{x: f32, y: f32};

const DEFAULT_VEL: Velocity2D = Velocity2D {x: 0.0, y: 0.0};

impl Default for &Velocity2D {
    fn default() -> Self {
        &DEFAULT_VEL
    }
}

fn example(query: Query<OrDefault<&Velocity2D>>) {
    let _: &Velocity2D = query.get_single().unwrap();
}

Aliased Type§

struct OrDefault<T>(/* private fields */);