Skip to content

Commit fd32c6f

Browse files
authored
Simplify setup_scene_once_loaded in animated_fox (#8999)
# Objective The setup code in `animated_fox` uses a `done` boolean to avoid running the `play` logic repetitively. It is a common pattern, but it just work with exactly one fox, and misses an even more common pattern. When a user modifies the code to try it with several foxes, they are confused as to why it doesn't work (#8996). ## Solution The more common pattern is to use `Added<AnimationPlayer>` as a query filter. This both reduces complexity and naturally extend the setup code to handle several foxes, added at any time.
1 parent bcf53b8 commit fd32c6f

File tree

1 file changed

+5
-9
lines changed

1 file changed

+5
-9
lines changed

examples/animation/animated_fox.rs

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -83,24 +83,20 @@ fn setup(
8383
// Once the scene is loaded, start the animation
8484
fn setup_scene_once_loaded(
8585
animations: Res<Animations>,
86-
mut player: Query<&mut AnimationPlayer>,
87-
mut done: Local<bool>,
86+
mut players: Query<&mut AnimationPlayer, Added<AnimationPlayer>>,
8887
) {
89-
if !*done {
90-
if let Ok(mut player) = player.get_single_mut() {
91-
player.play(animations.0[0].clone_weak()).repeat();
92-
*done = true;
93-
}
88+
for mut player in &mut players {
89+
player.play(animations.0[0].clone_weak()).repeat();
9490
}
9591
}
9692

9793
fn keyboard_animation_control(
9894
keyboard_input: Res<Input<KeyCode>>,
99-
mut animation_player: Query<&mut AnimationPlayer>,
95+
mut animation_players: Query<&mut AnimationPlayer>,
10096
animations: Res<Animations>,
10197
mut current_animation: Local<usize>,
10298
) {
103-
if let Ok(mut player) = animation_player.get_single_mut() {
99+
for mut player in &mut animation_players {
104100
if keyboard_input.just_pressed(KeyCode::Space) {
105101
if player.is_paused() {
106102
player.resume();

0 commit comments

Comments
 (0)