Struct bevy::ecs::prelude::QueryState

#[repr(C)]
pub struct QueryState<D, F = ()>
where D: QueryData, F: QueryFilter,
{ /* private fields */ }
Expand description

Provides scoped access to a World state according to a given QueryData and QueryFilter.

This data is cached between system runs, and is used to:

  • store metadata about which Table or Archetype are matched by the query. “Matched” means that the query will iterate over the data in the matched table/archetype.
  • cache the State needed to compute the Fetch struct used to retrieve data from a specific Table or Archetype
  • build iterators that can iterate over the query results

Implementations§

§

impl<D, F> QueryState<D, F>
where D: QueryData, F: QueryFilter,

pub fn as_readonly(&self) -> &QueryState<<D as QueryData>::ReadOnly, F>

Converts this QueryState reference to a QueryState that does not access anything mutably.

pub fn component_access(&self) -> &FilteredAccess<ComponentId>

Returns the components accessed by this query.

pub fn matched_tables(&self) -> impl Iterator<Item = TableId>

Returns the tables matched by this query.

pub fn matched_archetypes(&self) -> impl Iterator<Item = ArchetypeId>

Returns the archetypes matched by this query.

§

impl<D, F> QueryState<D, F>
where D: QueryData, F: QueryFilter,

pub fn new(world: &mut World) -> QueryState<D, F>

Creates a new QueryState from a given World and inherits the result of world.id().

pub fn from_builder(builder: &mut QueryBuilder<'_, D, F>) -> QueryState<D, F>

Creates a new QueryState from a given QueryBuilder and inherits its FilteredAccess.

pub fn is_empty(&self, world: &World, last_run: Tick, this_run: Tick) -> bool

Checks if the query is empty for the given World, where the last change and current tick are given.

This is equivalent to self.iter().next().is_none(), and thus the worst case runtime will be O(n) where n is the number of potential matches. This can be notably expensive for queries that rely on non-archetypal filters such as Added or Changed which must individually check each query result for a match.

§Panics

If world does not match the one used to call QueryState::new for this instance.

pub fn contains( &self, entity: Entity, world: &World, last_run: Tick, this_run: Tick, ) -> bool

Returns true if the given Entity matches the query.

This is always guaranteed to run in O(1) time.

pub fn update_archetypes(&mut self, world: &World)

Updates the state’s internal view of the World’s archetypes. If this is not called before querying data, the results may not accurately reflect what is in the world.

This is only required if a manual method (such as Self::get_manual) is being called, and it only needs to be called if the world has been structurally mutated (i.e. added/removed a component or resource). Users using non-manual methods such as QueryState::get do not need to call this as it will be automatically called for them.

If you have an UnsafeWorldCell instead of &World, consider using QueryState::update_archetypes_unsafe_world_cell.

§Panics

If world does not match the one used to call QueryState::new for this instance.

pub fn update_archetypes_unsafe_world_cell( &mut self, world: UnsafeWorldCell<'_>, )

Updates the state’s internal view of the world’s archetypes. If this is not called before querying data, the results may not accurately reflect what is in the world.

This is only required if a manual method (such as Self::get_manual) is being called, and it only needs to be called if the world has been structurally mutated (i.e. added/removed a component or resource). Users using non-manual methods such as QueryState::get do not need to call this as it will be automatically called for them.

§Note

This method only accesses world metadata.

§Panics

If world does not match the one used to call QueryState::new for this instance.

pub fn validate_world(&self, world_id: WorldId)

§Panics

If world_id does not match the World used to call QueryState::new for this instance.

Many unsafe query methods require the world to match for soundness. This function is the easiest way of ensuring that it matches.

pub unsafe fn new_archetype( &mut self, archetype: &Archetype, access: &mut Access<ArchetypeComponentId>, )

Update the current QueryState with information from the provided Archetype (if applicable, i.e. if the archetype has any intersecting ComponentId with the current QueryState).

The passed in access will be updated with any new accesses introduced by the new archetype.

§Safety

archetype must be from the World this state was initialized from.

pub fn matches_component_set( &self, set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool

Returns true if this query matches a set of components. Otherwise, returns false.

pub unsafe fn update_archetype_component_access( &mut self, archetype: &Archetype, access: &mut Access<ArchetypeComponentId>, )

For the given archetype, adds any component accessed used by this query’s underlying FilteredAccess to access.

The passed in access will be updated with any new accesses introduced by the new archetype.

§Safety

archetype must be from the World this state was initialized from.

pub fn transmute<NewD>(&self, components: &Components) -> QueryState<NewD>
where NewD: QueryData,

Use this to transform a QueryState into a more generic QueryState. This can be useful for passing to another function that might take the more general form. See Query::transmute_lens for more details.

You should not call update_archetypes on the returned QueryState as the result will be unpredictable. You might end up with a mix of archetypes that only matched the original query + archetypes that only match the new QueryState. Most of the safe methods on QueryState call QueryState::update_archetypes internally, so this best used through a Query.

pub fn transmute_filtered<NewD, NewF>( &self, components: &Components, ) -> QueryState<NewD, NewF>
where NewD: QueryData, NewF: QueryFilter,

Creates a new QueryState with the same underlying FilteredAccess, matched tables and archetypes as self but with a new type signature.

Panics if NewD or NewF require accesses that this query does not have.

pub fn join<OtherD, NewD>( &self, components: &Components, other: &QueryState<OtherD>, ) -> QueryState<NewD>
where OtherD: QueryData, NewD: QueryData,

Use this to combine two queries. The data accessed will be the intersection of archetypes included in both queries. This can be useful for accessing a subset of the entities between two queries.

You should not call update_archetypes on the returned QueryState as the result could be unpredictable. You might end up with a mix of archetypes that only matched the original query + archetypes that only match the new QueryState. Most of the safe methods on QueryState call QueryState::update_archetypes internally, so this is best used through a Query.

§Performance

This will have similar performance as constructing a new QueryState since much of internal state needs to be reconstructed. But it will be a little faster as it only needs to compare the intersection of matching archetypes rather than iterating over all archetypes.

§Panics

Will panic if NewD contains accesses not in Q or OtherQ.

pub fn join_filtered<OtherD, OtherF, NewD, NewF>( &self, components: &Components, other: &QueryState<OtherD, OtherF>, ) -> QueryState<NewD, NewF>
where OtherD: QueryData, OtherF: QueryFilter, NewD: QueryData, NewF: QueryFilter,

Use this to combine two queries. The data accessed will be the intersection of archetypes included in both queries.

§Panics

Will panic if NewD or NewF requires accesses not in Q or OtherQ.

pub fn get<'w>( &mut self, world: &'w World, entity: Entity, ) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'w>, QueryEntityError>

Gets the query result for the given World and Entity.

This can only be called for read-only queries, see Self::get_mut for write-queries.

This is always guaranteed to run in O(1) time.

pub fn get_many<'w, const N: usize>( &mut self, world: &'w World, entities: [Entity; N], ) -> Result<[<<D as QueryData>::ReadOnly as WorldQuery>::Item<'w>; N], QueryEntityError>

Returns the read-only query results for the given array of Entity.

In case of a nonexisting entity or mismatched component, a QueryEntityError is returned instead.

Note that the unlike QueryState::get_many_mut, the entities passed in do not need to be unique.

§Examples
use bevy_ecs::prelude::*;
use bevy_ecs::query::QueryEntityError;

#[derive(Component, PartialEq, Debug)]
struct A(usize);

let mut world = World::new();
let entity_vec: Vec<Entity> = (0..3).map(|i|world.spawn(A(i)).id()).collect();
let entities: [Entity; 3] = entity_vec.try_into().unwrap();

world.spawn(A(73));

let mut query_state = world.query::<&A>();

let component_values = query_state.get_many(&world, entities).unwrap();

assert_eq!(component_values, [&A(0), &A(1), &A(2)]);

let wrong_entity = Entity::from_raw(365);

assert_eq!(query_state.get_many(&world, [wrong_entity]), Err(QueryEntityError::NoSuchEntity(wrong_entity)));

pub fn get_mut<'w>( &mut self, world: &'w mut World, entity: Entity, ) -> Result<<D as WorldQuery>::Item<'w>, QueryEntityError>

Gets the query result for the given World and Entity.

This is always guaranteed to run in O(1) time.

pub fn get_many_mut<'w, const N: usize>( &mut self, world: &'w mut World, entities: [Entity; N], ) -> Result<[<D as WorldQuery>::Item<'w>; N], QueryEntityError>

Returns the query results for the given array of Entity.

In case of a nonexisting entity or mismatched component, a QueryEntityError is returned instead.

use bevy_ecs::prelude::*;
use bevy_ecs::query::QueryEntityError;

#[derive(Component, PartialEq, Debug)]
struct A(usize);

let mut world = World::new();

let entities: Vec<Entity> = (0..3).map(|i|world.spawn(A(i)).id()).collect();
let entities: [Entity; 3] = entities.try_into().unwrap();

world.spawn(A(73));

let mut query_state = world.query::<&mut A>();

let mut mutable_component_values = query_state.get_many_mut(&mut world, entities).unwrap();

for mut a in &mut mutable_component_values {
    a.0 += 5;
}

let component_values = query_state.get_many(&world, entities).unwrap();

assert_eq!(component_values, [&A(5), &A(6), &A(7)]);

let wrong_entity = Entity::from_raw(57);
let invalid_entity = world.spawn_empty().id();

assert_eq!(query_state.get_many_mut(&mut world, [wrong_entity]).unwrap_err(), QueryEntityError::NoSuchEntity(wrong_entity));
assert_eq!(query_state.get_many_mut(&mut world, [invalid_entity]).unwrap_err(), QueryEntityError::QueryDoesNotMatch(invalid_entity));
assert_eq!(query_state.get_many_mut(&mut world, [entities[0], entities[0]]).unwrap_err(), QueryEntityError::AliasedMutability(entities[0]));

pub fn get_manual<'w>( &self, world: &'w World, entity: Entity, ) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'w>, QueryEntityError>

Gets the query result for the given World and Entity.

This method is slightly more efficient than QueryState::get in some situations, since it does not update this instance’s internal cache. This method will return an error if entity belongs to an archetype that has not been cached.

To ensure that the cache is up to date, call QueryState::update_archetypes before this method. The cache is also updated in QueryState::new, QueryState::get, or any method with mutable access to self.

This can only be called for read-only queries, see Self::get_mut for mutable queries.

This is always guaranteed to run in O(1) time.

pub unsafe fn get_unchecked<'w>( &mut self, world: UnsafeWorldCell<'w>, entity: Entity, ) -> Result<<D as WorldQuery>::Item<'w>, QueryEntityError>

Gets the query result for the given World and Entity.

This is always guaranteed to run in O(1) time.

§Safety

This does not check for mutable query correctness. To be safe, make sure mutable queries have unique access to the components they query.

pub fn iter<'w, 's>( &'s mut self, world: &'w World, ) -> QueryIter<'w, 's, <D as QueryData>::ReadOnly, F>

Returns an Iterator over the query results for the given World.

This can only be called for read-only queries, see Self::iter_mut for write-queries.

Examples found in repository?
examples/tools/scene_viewer/scene_viewer_plugin.rs (line 122)
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
fn scene_load_check(
    asset_server: Res<AssetServer>,
    mut scenes: ResMut<Assets<Scene>>,
    gltf_assets: Res<Assets<Gltf>>,
    mut scene_handle: ResMut<SceneHandle>,
    mut scene_spawner: ResMut<SceneSpawner>,
) {
    match scene_handle.instance_id {
        None => {
            if asset_server.load_state(&scene_handle.gltf_handle) == LoadState::Loaded {
                let gltf = gltf_assets.get(&scene_handle.gltf_handle).unwrap();
                if gltf.scenes.len() > 1 {
                    info!(
                        "Displaying scene {} out of {}",
                        scene_handle.scene_index,
                        gltf.scenes.len()
                    );
                    info!("You can select the scene by adding '#Scene' followed by a number to the end of the file path (e.g '#Scene1' to load the second scene).");
                }

                let gltf_scene_handle =
                    gltf.scenes
                        .get(scene_handle.scene_index)
                        .unwrap_or_else(|| {
                            panic!(
                                "glTF file doesn't contain scene {}!",
                                scene_handle.scene_index
                            )
                        });
                let scene = scenes.get_mut(gltf_scene_handle).unwrap();

                let mut query = scene
                    .world
                    .query::<(Option<&DirectionalLight>, Option<&PointLight>)>();
                scene_handle.has_light =
                    query
                        .iter(&scene.world)
                        .any(|(maybe_directional_light, maybe_point_light)| {
                            maybe_directional_light.is_some() || maybe_point_light.is_some()
                        });

                scene_handle.instance_id =
                    Some(scene_spawner.spawn(gltf_scene_handle.clone_weak()));

                info!("Spawning scene...");
            }
        }
        Some(instance_id) if !scene_handle.is_loaded => {
            if scene_spawner.instance_is_ready(instance_id) {
                info!("...done!");
                scene_handle.is_loaded = true;
            }
        }
        Some(_) => {}
    }
}

pub fn iter_mut<'w, 's>( &'s mut self, world: &'w mut World, ) -> QueryIter<'w, 's, D, F>

Returns an Iterator over the query results for the given World.

This iterator is always guaranteed to return results from each matching entity once and only once. Iteration order is not guaranteed.

Examples found in repository?
examples/ecs/dynamic.rs (line 152)
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
fn main() {
    let mut world = World::new();
    let mut lines = std::io::stdin().lines();
    let mut component_names = HashMap::<String, ComponentId>::new();
    let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();

    println!("{}", PROMPT);
    loop {
        print!("\n> ");
        let _ = std::io::stdout().flush();
        let Some(Ok(line)) = lines.next() else {
            return;
        };

        if line.is_empty() {
            return;
        };

        let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
            match &line.chars().next() {
                Some('c') => println!("{}", COMPONENT_PROMPT),
                Some('s') => println!("{}", ENTITY_PROMPT),
                Some('q') => println!("{}", QUERY_PROMPT),
                _ => println!("{}", PROMPT),
            }
            continue;
        };

        match &first[0..1] {
            "c" => {
                rest.split(',').for_each(|component| {
                    let mut component = component.split_whitespace();
                    let Some(name) = component.next() else {
                        return;
                    };
                    let size = match component.next().map(|s| s.parse::<usize>()) {
                        Some(Ok(size)) => size,
                        _ => 0,
                    };
                    // Register our new component to the world with a layout specified by it's size
                    // SAFETY: [u64] is Send + Sync
                    let id = world.init_component_with_descriptor(unsafe {
                        ComponentDescriptor::new_with_layout(
                            name.to_string(),
                            StorageType::Table,
                            Layout::array::<u64>(size).unwrap(),
                            None,
                        )
                    });
                    let Some(info) = world.components().get_info(id) else {
                        return;
                    };
                    component_names.insert(name.to_string(), id);
                    component_info.insert(id, info.clone());
                    println!("Component {} created with id: {:?}", name, id.index());
                });
            }
            "s" => {
                let mut to_insert_ids = Vec::new();
                let mut to_insert_data = Vec::new();
                rest.split(',').for_each(|component| {
                    let mut component = component.split_whitespace();
                    let Some(name) = component.next() else {
                        return;
                    };

                    // Get the id for the component with the given name
                    let Some(&id) = component_names.get(name) else {
                        println!("Component {} does not exist", name);
                        return;
                    };

                    // Calculate the length for the array based on the layout created for this component id
                    let info = world.components().get_info(id).unwrap();
                    let len = info.layout().size() / std::mem::size_of::<u64>();
                    let mut values: Vec<u64> = component
                        .take(len)
                        .filter_map(|value| value.parse::<u64>().ok())
                        .collect();
                    values.resize(len, 0);

                    // Collect the id and array to be inserted onto our entity
                    to_insert_ids.push(id);
                    to_insert_data.push(values);
                });

                let mut entity = world.spawn_empty();

                // Construct an `OwningPtr` for each component in `to_insert_data`
                let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);

                // SAFETY:
                // - Component ids have been taken from the same world
                // - Each array is created to the layout specified in the world
                unsafe {
                    entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
                }

                println!("Entity spawned with id: {:?}", entity.id());
            }
            "q" => {
                let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
                parse_query(rest, &mut builder, &component_names);
                let mut query = builder.build();

                query.iter_mut(&mut world).for_each(|filtered_entity| {
                    let terms = filtered_entity
                        .components()
                        .map(|id| {
                            let ptr = filtered_entity.get_by_id(id).unwrap();
                            let info = component_info.get(&id).unwrap();
                            let len = info.layout().size() / std::mem::size_of::<u64>();

                            // SAFETY:
                            // - All components are created with layout [u64]
                            // - len is calculated from the component descriptor
                            let data = unsafe {
                                std::slice::from_raw_parts_mut(
                                    ptr.assert_unique().as_ptr().cast::<u64>(),
                                    len,
                                )
                            };

                            // If we have write access, increment each value once
                            if filtered_entity.access().has_write(id) {
                                data.iter_mut().for_each(|data| {
                                    *data += 1;
                                });
                            }

                            format!("{}: {:?}", info.name(), data[0..len].to_vec())
                        })
                        .collect::<Vec<_>>()
                        .join(", ");

                    println!("{:?}: {}", filtered_entity.id(), terms);
                });
            }
            _ => continue,
        }
    }
}

pub fn iter_manual<'w, 's>( &'s self, world: &'w World, ) -> QueryIter<'w, 's, <D as QueryData>::ReadOnly, F>

Returns an Iterator over the query results for the given World without updating the query’s archetypes. Archetypes must be manually updated before by using Self::update_archetypes.

This iterator is always guaranteed to return results from each matching entity once and only once. Iteration order is not guaranteed.

This can only be called for read-only queries.

pub fn iter_combinations<'w, 's, const K: usize>( &'s mut self, world: &'w World, ) -> QueryCombinationIter<'w, 's, <D as QueryData>::ReadOnly, F, K>

Returns an Iterator over all possible combinations of K query results without repetition. This can only be called for read-only queries.

A combination is an arrangement of a collection of items where order does not matter.

K is the number of items that make up each subset, and the number of items returned by the iterator. N is the number of total entities output by query.

For example, given the list [1, 2, 3, 4], where K is 2, the combinations without repeats are [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]. And in this case, N would be defined as 4 since the size of the input list is 4.

For combinations of size K of query taking N inputs, you will get:

  • if K == N: one combination of all query results
  • if K < N: all possible K-sized combinations of query results, without repetition
  • if K > N: empty set (no K-sized combinations exist)

The iter_combinations method does not guarantee order of iteration.

This iterator is always guaranteed to return results from each unique pair of matching entities. Iteration order is not guaranteed.

This can only be called for read-only queries, see Self::iter_combinations_mut for write-queries.

pub fn iter_combinations_mut<'w, 's, const K: usize>( &'s mut self, world: &'w mut World, ) -> QueryCombinationIter<'w, 's, D, F, K>

Returns an Iterator over all possible combinations of K query results without repetition.

A combination is an arrangement of a collection of items where order does not matter.

K is the number of items that make up each subset, and the number of items returned by the iterator. N is the number of total entities output by query.

For example, given the list [1, 2, 3, 4], where K is 2, the combinations without repeats are [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]. And in this case, N would be defined as 4 since the size of the input list is 4.

For combinations of size K of query taking N inputs, you will get:

  • if K == N: one combination of all query results
  • if K < N: all possible K-sized combinations of query results, without repetition
  • if K > N: empty set (no K-sized combinations exist)

The iter_combinations_mut method does not guarantee order of iteration.

pub fn iter_many<'w, 's, EntityList>( &'s mut self, world: &'w World, entities: EntityList, ) -> QueryManyIter<'w, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter>
where EntityList: IntoIterator, <EntityList as IntoIterator>::Item: Borrow<Entity>,

Returns an Iterator over the read-only query items generated from an Entity list.

Items are returned in the order of the list of entities. Entities that don’t match the query are skipped.

§See also

pub fn iter_many_manual<'w, 's, EntityList>( &'s self, world: &'w World, entities: EntityList, ) -> QueryManyIter<'w, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter>
where EntityList: IntoIterator, <EntityList as IntoIterator>::Item: Borrow<Entity>,

Returns an Iterator over the read-only query items generated from an Entity list.

Items are returned in the order of the list of entities. Entities that don’t match the query are skipped.

If world archetypes changed since Self::update_archetypes was last called, this will skip entities contained in new archetypes.

This can only be called for read-only queries.

§See also

pub fn iter_many_mut<'w, 's, EntityList>( &'s mut self, world: &'w mut World, entities: EntityList, ) -> QueryManyIter<'w, 's, D, F, <EntityList as IntoIterator>::IntoIter>
where EntityList: IntoIterator, <EntityList as IntoIterator>::Item: Borrow<Entity>,

Returns an iterator over the query items generated from an Entity list.

Items are returned in the order of the list of entities. Entities that don’t match the query are skipped.

pub unsafe fn iter_unchecked<'w, 's>( &'s mut self, world: UnsafeWorldCell<'w>, ) -> QueryIter<'w, 's, D, F>

Returns an Iterator over the query results for the given World.

This iterator is always guaranteed to return results from each matching entity once and only once. Iteration order is not guaranteed.

§Safety

This does not check for mutable query correctness. To be safe, make sure mutable queries have unique access to the components they query.

pub unsafe fn iter_combinations_unchecked<'w, 's, const K: usize>( &'s mut self, world: UnsafeWorldCell<'w>, ) -> QueryCombinationIter<'w, 's, D, F, K>

Returns an Iterator over all possible combinations of K query results for the given World without repetition. This can only be called for read-only queries.

This iterator is always guaranteed to return results from each unique pair of matching entities. Iteration order is not guaranteed.

§Safety

This does not check for mutable query correctness. To be safe, make sure mutable queries have unique access to the components they query.

pub fn par_iter<'w, 's>( &'s mut self, world: &'w World, ) -> QueryParIter<'w, 's, <D as QueryData>::ReadOnly, F>

Returns a parallel iterator over the query results for the given World.

This can only be called for read-only queries, see par_iter_mut for write-queries.

Note that you must use the for_each method to iterate over the results, see par_iter_mut for an example.

pub fn par_iter_mut<'w, 's>( &'s mut self, world: &'w mut World, ) -> QueryParIter<'w, 's, D, F>

Returns a parallel iterator over the query results for the given World.

This can only be called for mutable queries, see par_iter for read-only-queries.

§Examples
use bevy_ecs::prelude::*;
use bevy_ecs::query::QueryEntityError;

#[derive(Component, PartialEq, Debug)]
struct A(usize);


let mut world = World::new();


let mut query_state = world.query::<&mut A>();

query_state.par_iter_mut(&mut world).for_each(|mut a| {
    a.0 += 5;
});



§Panics

The ComputeTaskPool is not initialized. If using this from a query that is being initialized and run from the ECS scheduler, this should never panic.

pub fn single<'w>( &mut self, world: &'w World, ) -> <<D as QueryData>::ReadOnly as WorldQuery>::Item<'w>

Returns a single immutable query result when there is exactly one entity matching the query.

This can only be called for read-only queries, see single_mut for write-queries.

§Panics

Panics if the number of query results is not exactly one. Use get_single to return a Result instead of panicking.

pub fn get_single<'w>( &mut self, world: &'w World, ) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'w>, QuerySingleError>

Returns a single immutable query result when there is exactly one entity matching the query.

This can only be called for read-only queries, see get_single_mut for write-queries.

If the number of query results is not exactly one, a QuerySingleError is returned instead.

pub fn single_mut<'w>( &mut self, world: &'w mut World, ) -> <D as WorldQuery>::Item<'w>

Returns a single mutable query result when there is exactly one entity matching the query.

§Panics

Panics if the number of query results is not exactly one. Use get_single_mut to return a Result instead of panicking.

pub fn get_single_mut<'w>( &mut self, world: &'w mut World, ) -> Result<<D as WorldQuery>::Item<'w>, QuerySingleError>

Returns a single mutable query result when there is exactly one entity matching the query.

If the number of query results is not exactly one, a QuerySingleError is returned instead.

pub unsafe fn get_single_unchecked<'w>( &mut self, world: UnsafeWorldCell<'w>, ) -> Result<<D as WorldQuery>::Item<'w>, QuerySingleError>

Returns a query result when there is exactly one entity matching the query.

If the number of query results is not exactly one, a QuerySingleError is returned instead.

§Safety

This does not check for mutable query correctness. To be safe, make sure mutable queries have unique access to the components they query.

pub unsafe fn get_single_unchecked_manual<'w>( &self, world: UnsafeWorldCell<'w>, last_run: Tick, this_run: Tick, ) -> Result<<D as WorldQuery>::Item<'w>, QuerySingleError>

Returns a query result when there is exactly one entity matching the query, where the last change and the current change tick are given.

If the number of query results is not exactly one, a QuerySingleError is returned instead.

§Safety

This does not check for mutable query correctness. To be safe, make sure mutable queries have unique access to the components they query.

Trait Implementations§

§

impl<D, F> Debug for QueryState<D, F>
where D: QueryData, F: QueryFilter,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<'a, D, F> ExclusiveSystemParam for &'a mut QueryState<D, F>
where D: QueryData + 'static, F: QueryFilter + 'static,

§

type State = QueryState<D, F>

Used to store data which persists across invocations of a system.
§

type Item<'s> = &'s mut QueryState<D, F>

The item type returned when constructing this system param. See SystemParam::Item.
§

fn init( world: &mut World, _system_meta: &mut SystemMeta, ) -> <&'a mut QueryState<D, F> as ExclusiveSystemParam>::State

Creates a new instance of this param’s State.
§

fn get_param<'s>( state: &'s mut <&'a mut QueryState<D, F> as ExclusiveSystemParam>::State, _system_meta: &SystemMeta, ) -> <&'a mut QueryState<D, F> as ExclusiveSystemParam>::Item<'s>

Creates a parameter to be passed into an ExclusiveSystemParamFunction.
§

impl<D, F> From<QueryBuilder<'_, D, F>> for QueryState<D, F>
where D: QueryData, F: QueryFilter,

§

fn from(value: QueryBuilder<'_, D, F>) -> QueryState<D, F>

Converts to this type from the input type.
§

impl<D, F> FromWorld for QueryState<D, F>
where D: QueryData, F: QueryFilter,

§

fn from_world(world: &mut World) -> QueryState<D, F>

Creates Self using data from the given World.

Auto Trait Implementations§

§

impl<D, F> Freeze for QueryState<D, F>
where <D as WorldQuery>::State: Freeze, <F as WorldQuery>::State: Freeze,

§

impl<D, F = ()> !RefUnwindSafe for QueryState<D, F>

§

impl<D, F> Send for QueryState<D, F>

§

impl<D, F> Sync for QueryState<D, F>

§

impl<D, F> Unpin for QueryState<D, F>
where <D as WorldQuery>::State: Unpin, <F as WorldQuery>::State: Unpin,

§

impl<D, F = ()> !UnwindSafe for QueryState<D, F>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<S> FromSample<S> for S

§

fn from_sample_(s: S) -> S

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

§

fn into_sample(self) -> T

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

§

fn to_sample_(self) -> U

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
§

impl<T> ConditionalSend for T
where T: Send,

§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

§

impl<T> Settings for T
where T: 'static + Send + Sync,

§

impl<T> WasmNotSend for T
where T: Send,

§

impl<T> WasmNotSendSync for T
where T: WasmNotSend + WasmNotSync,

§

impl<T> WasmNotSync for T
where T: Sync,