-
I want to write a system that takes in a query for all entities with two specific components: use bevy::ecs::component::Component;
use bevy::prelude::Query;
fn my_system(_: Query<&A, &B>) { /* execute systems logic */ }
#[derive(Component)]
struct A;
#[derive(Component)]
struct B; This doesn't compile with the following error:
I don't really get the error. Why does it expect a |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
You should write
fn my_system(query: Query<&Transform>) {
for transform in query.iter() {
//...
}
} Here the "query item" (what the query returns) is of type
// now with filter, only retrieve cameras
fn my_system(query: Query<&Transform, With<Camera>>) {
for transform in query.iter() {
//...
}
} It is especially useful in combination with a marker component. #[derive(Component)]
struct MyMarker;
// now with filter, only retrieve entities that have MyMarker component
// Since we do not care about the value of the MyMarker component (because
// it will always be the same), we just use it as a filter in combination with `With`
fn my_system(query: Query<&Transform, With<MyMarker>>) {
for transform in query.iter() {
//...
}
} The query is filtered based on the "query item" of the filter, which is a true/false answer to the question: should this item be in the Now what you want is two different components, so you'll want your "query item" to be the two components in a tuple. To do this, you'll have the // notice the parenthesis
fn my_system(query: Query<(&A, &B)>) {
for (a, b) in query.iter() {
//...
}
} |
Beta Was this translation helpful? Give feedback.
-
The correct syntax is: fn my_system(_: Query<(&A, &B)>) { /* execute systems logic */ } This is a bit confusing, so let's start at the beginning. Query has two (non-lifetime) type parameters: Each time you use a top-level comma, you're moving onto the next type parameter. However, we use tuples to allow you to create compound types, for "fetch me A and B". Finally, we use a default type parameter for |
Beta Was this translation helpful? Give feedback.
You should write
Query<(&A, &B)>
instead ofQuery<&A, &B>
.Query<C, F>
is a generic type that accepts two type parameters:C
: What you want to query forF
: The filters, that can limit what will be in the query.C
will be the things you get in the for loop when iterating over the query:Here the "query item" (what the query returns) is of type
Transform
, and you get aTransform
when usingquery.iter()
orquery.get
.F
are "filter", you still get the query items do not change, but the filters limit which items are retrieved: