Change detection
React to components and resources that were added, changed or removed, avoid false changes with set_if_neq, and find out where a change came from.
On this page
The engine records when every component and resource was added and when it was last written. Systems can use that to do work only when something actually changed: update a health bar when health changes, rebuild a mesh when its settings change, save when the settings resource changes.
Changes are counted per system. Each system sees a change once, the next time it runs after the change.
Ways to react to changes#
| Tool | Use it for |
|---|---|
Changed<T>, Added<T> query filters | Iterating only the entities whose T changed or was added. |
Ref<T> in a query | Reading T along with is_added() and is_changed(), without filtering. |
res.is_changed(), res.is_added() | The same for a resource. |
resource_changed::<T> and friends | Run conditions that skip a system unless a resource changed. |
RemovedComponents<T> | Entities that lost a T (or were despawned with one) since the system last ran. |
| Lifecycle observers and hooks | Running code immediately when a component is added, replaced or removed. |
Changed components#
use neo::prelude::*;
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct HealthBar;
fn update_bars(changed: Query<(&Health, &Children), Changed<Health>>, mut bars: Query<&mut Text, With<HealthBar>>) {
for (health, children) in &changed {
for child in children {
if let Ok(mut text) = bars.get_mut(*child) {
*text = Text::new(format!("{}", health.0));
}
}
}
}Ref<T> gives you the flags without filtering:
fn log_changes(query: Query<(Entity, Ref<Health>)>) {
for (entity, health) in &query {
if health.is_added() {
info!("{entity} spawned with {} health", health.0);
} else if health.is_changed() {
info!("{entity} now has {} health", health.0);
}
}
}Changed resources#
Res<T> and ResMut<T> have the same methods:
#[derive(Resource, PartialEq)]
struct Volume(f32);
fn apply_volume(volume: Res<Volume>) {
if volume.is_changed() {
info!("volume is now {}", volume.0);
}
}What counts as a change#
A component or resource is marked changed when it is written through Mut<T> or ResMut<T>, that is, on any mutable dereference. The engine doesn't compare values, so assigning the same value still counts.
| Method | What it does |
|---|---|
value.set_if_neq(new) | Writes new only if it differs (T: PartialEq), so equal values don't mark a change. |
value.replace_if_neq(new) | The same, returning the old value when it changed. |
value.bypass_change_detection() | A &mut T that writes without marking a change. Use it sparingly. |
value.set_changed() | Marks a change without writing. |
value.last_changed() | The tick of the last change. |
fn clamp_health(mut query: Query<&mut Health>) {
for mut health in &mut query {
// `health.0 = health.0.min(100)` would mark every entity changed
let clamped = health.0.min(100);
if health.0 != clamped {
health.0 = clamped;
}
}
}Fetching &mut T in a query without writing to it doesn't mark anything; only the write does.
Removed components#
RemovedComponents<T> lists the entities that lost a T recently, including entities that were despawned:
fn on_health_removed(mut removed: RemovedComponents<Health>) {
for entity in removed.read() {
info!("{entity} no longer has health");
}
}The component data is already gone when you read this. If you need the old value, use a Remove observer or an on_remove hook, which run before the component is dropped. Removals are kept for about two frames, so read them every frame.
Where did that change come from?#
With the track_location cargo feature, changed_by() on Ref, Mut, Res and ResMut returns the file and line that last changed the value, and spawn and despawn locations show up in errors. It costs memory and time, so it isn't on in NEO's builds; turn it on for a debugging session only.
cargo run --example change_detection --features track_locationRun it from the engine core's workspace. See Cargo features.