Tainted \\ Coders

Query for changed components

Last updated:

Use the Changed<T> type in a query.

fn change_detection(
    query: Query<(Entity, &Health), Changed<Health>>
) {
    for (entity, health) in &query {
        info!("{:?} changed: {:?}", entity, health);
    }
}

Here we are using the second generic parameter of our Query<Q, F> which is the filter to only return components for entities that have had their Health changed.

A component being changed simply means that it was derferenced at some point in the last loop. Bevy does not actually compare the value of the health component.

In terms of performance the Changed<T> filter is equivalent to iterating over each component and using Ref<T> to check for changes:

fn similar_change_detection(
    query: Query<(Entity, Ref<Health>)>
) {
    for (entity, health) in &query {
        if health.is_changed() {
            info!("{:?} changed: {:?}", entity, health);
        }
    }
}