| 1 |
|
| 2 |
|
| 3 |
use bevy::prelude::*; |
| 4 |
use rand::RngExt; |
| 5 |
|
| 6 |
fn main() { |
| 7 |
App::new() |
| 8 |
.add_plugins(DefaultPlugins) |
| 9 |
.add_systems(Startup, setup) |
| 10 |
.add_systems( |
| 11 |
Update, |
| 12 |
( |
| 13 |
change_component, |
| 14 |
change_component_2, |
| 15 |
change_resource, |
| 16 |
change_detection, |
| 17 |
), |
| 18 |
) |
| 19 |
.run(); |
| 20 |
} |
| 21 |
|
| 22 |
#[derive(Component, PartialEq, Debug)] |
| 23 |
struct MyComponent(f32); |
| 24 |
|
| 25 |
#[derive(Resource, PartialEq, Debug)] |
| 26 |
struct MyResource(f32); |
| 27 |
|
| 28 |
fn setup(mut commands: Commands) { |
| 29 |
|
| 30 |
|
| 31 |
commands.spawn(MyComponent(0.0)); |
| 32 |
commands.insert_resource(MyResource(0.0)); |
| 33 |
} |
| 34 |
|
| 35 |
fn change_component(time: Res<Time>, mut query: Query<(Entity, &mut MyComponent)>) { |
| 36 |
for (entity, mut component) in &mut query { |
| 37 |
if rand::rng().random_bool(0.1) { |
| 38 |
let new_component = MyComponent(time.elapsed_secs().round()); |
| 39 |
info!("New value: {new_component:?} {entity}"); |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
component.set_if_neq(new_component); |
| 45 |
} |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
fn change_component_2(time: Res<Time>, mut query: Query<(Entity, &mut MyComponent)>) { |
| 53 |
for (entity, mut component) in &mut query { |
| 54 |
if rand::rng().random_bool(0.1) { |
| 55 |
let new_component = MyComponent(time.elapsed_secs().round()); |
| 56 |
info!("New value: {new_component:?} {entity}"); |
| 57 |
component.set_if_neq(new_component); |
| 58 |
} |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
|
| 63 |
fn change_resource(time: Res<Time>, mut my_resource: ResMut<MyResource>) { |
| 64 |
if rand::rng().random_bool(0.1) { |
| 65 |
let new_resource = MyResource(time.elapsed_secs().round()); |
| 66 |
info!("New value: {new_resource:?}"); |
| 67 |
my_resource.set_if_neq(new_resource); |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
fn change_detection( |
| 77 |
changed_components: Query<Ref<MyComponent>, Changed<MyComponent>>, |
| 78 |
my_resource: Res<MyResource>, |
| 79 |
) { |
| 80 |
for component in &changed_components { |
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
warn!( |
| 86 |
"Change detected!\n\t-> value: {:?}\n\t-> added: {}\n\t-> changed: {}\n\t-> changed by: {}", |
| 87 |
component, |
| 88 |
component.is_added(), |
| 89 |
component.is_changed(), |
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
component.changed_by() |
| 94 |
); |
| 95 |
} |
| 96 |
|
| 97 |
if my_resource.is_changed() { |
| 98 |
warn!( |
| 99 |
"Change detected!\n\t-> value: {:?}\n\t-> added: {}\n\t-> changed: {}\n\t-> changed by: {}", |
| 100 |
my_resource, |
| 101 |
my_resource.is_added(), |
| 102 |
my_resource.is_changed(), |
| 103 |
my_resource.changed_by() |
| 104 |
); |
| 105 |
} |
| 106 |
} |