Struct bevy::app::App

pub struct App { /* private fields */ }
Expand description

App is the primary API for writing user applications. It automates the setup of a standard lifecycle and provides interface glue for plugins.

A single App can contain multiple SubApp instances, but App methods only affect the “main” one. To access a particular SubApp, use get_sub_app or get_sub_app_mut.

§Examples

Here is a simple “Hello World” Bevy app:

fn main() {
   App::new()
       .add_systems(Update, hello_world_system)
       .run();
}

fn hello_world_system() {
   println!("hello world");
}

Implementations§

§

impl App

pub fn new() -> App

Creates a new App with some default structure to enable core engine features. This is the preferred constructor for most use cases.

Examples found in repository?
examples/app/empty.rs (line 6)
5
6
7
fn main() {
    App::new().run();
}
More examples
Hide additional examples
examples/app/empty_defaults.rs (line 6)
5
6
7
fn main() {
    App::new().add_plugins(DefaultPlugins).run();
}
examples/hello_world.rs (line 6)
5
6
7
fn main() {
    App::new().add_systems(Update, hello_world_system).run();
}
examples/2d/2d_shapes.rs (line 9)
8
9
10
11
12
13
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
examples/2d/mesh2d.rs (line 6)
5
6
7
8
9
10
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
examples/2d/mesh2d_vertex_color_texture.rs (line 10)
9
10
11
12
13
14
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}

pub fn empty() -> App

Creates a new empty App with minimal default configuration.

Use this constructor if you want to customize scheduling, exit handling, cleanup, etc.

pub fn update(&mut self)

Runs the default schedules of all sub-apps (starting with the “main” app) once.

Examples found in repository?
examples/app/custom_loop.rs (line 17)
10
11
12
13
14
15
16
17
18
19
fn my_runner(mut app: App) {
    println!("Type stuff into the console");
    for line in io::stdin().lines() {
        {
            let mut input = app.world_mut().resource_mut::<Input>();
            input.0 = line.unwrap();
        }
        app.update();
    }
}
More examples
Hide additional examples
examples/ecs/send_and_receive_events.rs (line 46)
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
fn main() {
    let mut app = App::new();
    app.add_plugins(MinimalPlugins)
        .add_event::<DebugEvent>()
        .add_event::<A>()
        .add_event::<B>()
        .add_systems(Update, read_and_write_different_event_types)
        .add_systems(
            Update,
            (
                send_events,
                debug_events,
                send_and_receive_param_set,
                debug_events,
                send_and_receive_manual_event_reader,
                debug_events,
            )
                .chain(),
        );
    // We're just going to run a few frames, so we can see and understand the output.
    app.update();
    // By running for longer than one frame, we can see that we're caching our cursor in the event queue properly.
    app.update();
}
examples/time/time.rs (line 44)
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
fn runner(mut app: App) {
    banner();
    help();
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        if let Err(err) = line {
            println!("read err: {:#}", err);
            break;
        }
        match line.unwrap().as_str() {
            "" => {
                app.update();
            }
            "f" => {
                println!("FAST: setting relative speed to 2x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(2.0);
            }
            "n" => {
                println!("NORMAL: setting relative speed to 1x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(1.0);
            }
            "s" => {
                println!("SLOW: setting relative speed to 0.5x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(0.5);
            }
            "p" => {
                println!("PAUSE: pausing virtual clock");
                app.world_mut().resource_mut::<Time<Virtual>>().pause();
            }
            "u" => {
                println!("UNPAUSE: resuming virtual clock");
                app.world_mut().resource_mut::<Time<Virtual>>().unpause();
            }
            "q" => {
                println!("QUITTING!");
                break;
            }
            _ => {
                help();
            }
        }
    }
}
examples/ecs/system_stepping.rs (line 38)
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
fn main() {
    let mut app = App::new();

    app
        // to display log messages from Stepping resource
        .add_plugins(LogPlugin::default())
        .add_systems(
            Update,
            (
                update_system_one,
                // establish a dependency here to simplify descriptions below
                update_system_two.after(update_system_one),
                update_system_three.after(update_system_two),
                update_system_four,
            ),
        )
        .add_systems(PreUpdate, pre_update_system);

    // For the simplicity of this example, we directly modify the `Stepping`
    // resource here and run the systems with `App::update()`.  Each call to
    // `App::update()` is the equivalent of a single frame render when using
    // `App::run()`.
    //
    // In a real-world situation, the `Stepping` resource would be modified by
    // a system based on input from the user.  A full demonstration of this can
    // be found in the breakout example.
    println!(
        r#"
    Actions: call app.update()
     Result: All systems run normally"#
    );
    app.update();

    println!(
        r#"
    Actions: Add the Stepping resource then call app.update()
     Result: All systems run normally.  Stepping has no effect unless explicitly
             configured for a Schedule, and Stepping has been enabled."#
    );
    app.insert_resource(Stepping::new());
    app.update();

    println!(
        r#"
    Actions: Add the Update Schedule to Stepping; enable Stepping; call
             app.update()
     Result: Only the systems in PreUpdate run.  When Stepping is enabled,
             systems in the configured schedules will not run unless:
             * Stepping::step_frame() is called
             * Stepping::continue_frame() is called
             * System has been configured to always run"#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.add_schedule(Update).enable();
    app.update();

    println!(
        r#"
    Actions: call Stepping.step_frame(); call app.update()
     Result: The PreUpdate systems run, and one Update system will run.  In
             Stepping, step means run the next system across all the schedules 
             that have been added to the Stepping resource."#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.step_frame();
    app.update();

    println!(
        r#"
    Actions: call app.update()
     Result: Only the PreUpdate systems run.  The previous call to
             Stepping::step_frame() only applies for the next call to
             app.update()/the next frame rendered.
    "#
    );
    app.update();

    println!(
        r#"
    Actions: call Stepping::continue_frame(); call app.update()
     Result: PreUpdate system will run, and all remaining Update systems will
             run.  Stepping::continue_frame() tells stepping to run all systems
             starting after the last run system until it hits the end of the
             frame, or it encounters a system with a breakpoint set.  In this
             case, we previously performed a step, running one system in Update.
             This continue will cause all remaining systems in Update to run."#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.continue_frame();
    app.update();

    println!(
        r#"
    Actions: call Stepping::step_frame() & app.update() four times in a row
     Result: PreUpdate system runs every time we call app.update(), along with
             one system from the Update schedule each time.  This shows what
             execution would look like to step through an entire frame of 
             systems."#
    );
    for _ in 0..4 {
        let mut stepping = app.world_mut().resource_mut::<Stepping>();
        stepping.step_frame();
        app.update();
    }

    println!(
        r#"
    Actions: Stepping::always_run(Update, update_system_two); step through all
             systems
     Result: PreUpdate system and update_system_two() will run every time we
             call app.update().  We'll also only need to step three times to
             execute all systems in the frame.  Stepping::always_run() allows
             us to granularly allow systems to run when stepping is enabled."#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.always_run(Update, update_system_two);
    for _ in 0..3 {
        let mut stepping = app.world_mut().resource_mut::<Stepping>();
        stepping.step_frame();
        app.update();
    }

    println!(
        r#"
    Actions: Stepping::never_run(Update, update_system_two); continue through
             all systems
     Result: All systems except update_system_two() will execute.
             Stepping::never_run() allows us to disable systems while Stepping
             is enabled."#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.never_run(Update, update_system_two);
    stepping.continue_frame();
    app.update();

    println!(
        r#"
    Actions: Stepping::set_breakpoint(Update, update_system_two); continue,
             step, continue
     Result: During the first continue, pre_update_system() and
             update_system_one() will run.  update_system_four() may also run
             as it has no dependency on update_system_two() or
             update_system_three().  Nether update_system_two() nor
             update_system_three() will run in the first app.update() call as
             they form a chained dependency on update_system_one() and run
             in order of one, two, three.  Stepping stops system execution in
             the Update schedule when it encounters the breakpoint for
             update_system_three().
             During the step we run update_system_two() along with the
             pre_update_system().
             During the final continue pre_update_system() and
             update_system_three() run."#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.set_breakpoint(Update, update_system_two);
    stepping.continue_frame();
    app.update();
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.step_frame();
    app.update();
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.continue_frame();
    app.update();

    println!(
        r#"
    Actions: Stepping::clear_breakpoint(Update, update_system_two); continue
             through all systems
     Result: All systems will run"#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.clear_breakpoint(Update, update_system_two);
    stepping.continue_frame();
    app.update();

    println!(
        r#"
    Actions: Stepping::disable(); app.update()
     Result: All systems will run.  With Stepping disabled, there's no need to
             call Stepping::step_frame() or Stepping::continue_frame() to run
             systems in the Update schedule."#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.disable();
    app.update();
}

pub fn run(&mut self)

Runs the App by calling its runner.

This will (re)build the App first. For general usage, see the example on the item level documentation.

§Caveats

Calls to App::run() will never return on iOS and Web.

Headless apps can generally expect this method to return control to the caller when it completes, but that is not the case for windowed apps. Windowed apps are typically driven by an event loop and some platforms expect the program to terminate when the event loop ends.

By default, Bevy uses the winit crate for window creation.

§Panics

Panics if not all plugins have been built.

Examples found in repository?
examples/app/empty.rs (line 6)
5
6
7
fn main() {
    App::new().run();
}
More examples
Hide additional examples
examples/app/empty_defaults.rs (line 6)
5
6
7
fn main() {
    App::new().add_plugins(DefaultPlugins).run();
}
examples/hello_world.rs (line 6)
5
6
7
fn main() {
    App::new().add_systems(Update, hello_world_system).run();
}
examples/2d/2d_shapes.rs (line 12)
8
9
10
11
12
13
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
examples/2d/mesh2d.rs (line 9)
5
6
7
8
9
10
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
examples/2d/mesh2d_vertex_color_texture.rs (line 13)
9
10
11
12
13
14
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}

pub fn set_runner(&mut self, f: impl FnOnce(App) + 'static) -> &mut App

Sets the function that will be called when the app is run.

The runner function f is called only once by App::run. If the presence of a main loop in the app is desired, it is the responsibility of the runner function to provide it.

The runner function is usually not set manually, but by Bevy integrated plugins (e.g. WinitPlugin).

§Examples
fn my_runner(mut app: App) {
    loop {
        println!("In main loop");
        app.update();
    }
}

App::new()
    .set_runner(my_runner);
Examples found in repository?
examples/app/custom_loop.rs (line 28)
25
26
27
28
29
30
31
fn main() {
    App::new()
        .insert_resource(Input(String::new()))
        .set_runner(my_runner)
        .add_systems(Update, print_system)
        .run();
}
More examples
Hide additional examples
examples/time/time.rs (line 115)
107
108
109
110
111
112
113
114
115
116
117
fn main() {
    App::new()
        .add_plugins(MinimalPlugins)
        .insert_resource(Time::<Virtual>::from_max_delta(Duration::from_secs(5)))
        .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs(1)))
        .add_systems(PreUpdate, print_real_time)
        .add_systems(FixedUpdate, print_fixed_time)
        .add_systems(Update, print_time)
        .set_runner(runner)
        .run();
}

pub fn plugins_state(&mut self) -> PluginsState

Returns the state of all plugins. This is usually called by the event loop, but can be useful for situations where you want to use App::update.

pub fn finish(&mut self)

Runs Plugin::finish for each plugin. This is usually called by the event loop once all plugins are ready, but can be useful for situations where you want to use App::update.

pub fn cleanup(&mut self)

Runs Plugin::cleanup for each plugin. This is usually called by the event loop after App::finish, but can be useful for situations where you want to use App::update.

pub fn init_state<S>(&mut self) -> &mut App
where S: States + FromWorld,

Initializes a State with standard starting values.

If the State already exists, nothing happens.

Adds State<S> and NextState<S> resources, OnEnter and OnExit schedules for each state variant (if they don’t already exist), an instance of apply_state_transition::<S> in StateTransition so that transitions happen before Update and an instance of run_enter_schedule::<S> in StateTransition with a run_once condition to run the on enter schedule of the initial state.

If you would like to control how other systems run based on the current state, you can emulate this behavior using the in_state Condition.

Note that you can also apply state transitions at other points in the schedule by adding the apply_state_transition::<S> system manually.

Examples found in repository?
examples/2d/texture_atlas.rs (line 15)
12
13
14
15
16
17
18
19
20
fn main() {
    App::new()
        .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest())) // fallback to nearest sampling
        .init_state::<AppState>()
        .add_systems(OnEnter(AppState::Setup), load_textures)
        .add_systems(Update, check_textures.run_if(in_state(AppState::Setup)))
        .add_systems(OnEnter(AppState::Finished), setup)
        .run();
}
More examples
Hide additional examples
examples/games/game_menu.rs (line 37)
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        // Insert as resource the initial value for the settings resources
        .insert_resource(DisplayQuality::Medium)
        .insert_resource(Volume(7))
        // Declare the game state, whose starting value is determined by the `Default` trait
        .init_state::<GameState>()
        .add_systems(Startup, setup)
        // Adds the plugins for each state
        .add_plugins((splash::splash_plugin, menu::menu_plugin, game::game_plugin))
        .run();
}

fn setup(mut commands: Commands) {
    commands.spawn(Camera2dBundle::default());
}

mod splash {
    use bevy::prelude::*;

    use super::{despawn_screen, GameState};

    // This plugin will display a splash screen with Bevy logo for 1 second before switching to the menu
    pub fn splash_plugin(app: &mut App) {
        // As this plugin is managing the splash screen, it will focus on the state `GameState::Splash`
        app
            // When entering the state, spawn everything needed for this screen
            .add_systems(OnEnter(GameState::Splash), splash_setup)
            // While in this state, run the `countdown` system
            .add_systems(Update, countdown.run_if(in_state(GameState::Splash)))
            // When exiting the state, despawn everything that was spawned for this screen
            .add_systems(OnExit(GameState::Splash), despawn_screen::<OnSplashScreen>);
    }

    // Tag component used to tag entities added on the splash screen
    #[derive(Component)]
    struct OnSplashScreen;

    // Newtype to use a `Timer` for this screen as a resource
    #[derive(Resource, Deref, DerefMut)]
    struct SplashTimer(Timer);

    fn splash_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
        let icon = asset_server.load("branding/icon.png");
        // Display the logo
        commands
            .spawn((
                NodeBundle {
                    style: Style {
                        align_items: AlignItems::Center,
                        justify_content: JustifyContent::Center,
                        width: Val::Percent(100.0),
                        height: Val::Percent(100.0),
                        ..default()
                    },
                    ..default()
                },
                OnSplashScreen,
            ))
            .with_children(|parent| {
                parent.spawn(ImageBundle {
                    style: Style {
                        // This will set the logo to be 200px wide, and auto adjust its height
                        width: Val::Px(200.0),
                        ..default()
                    },
                    image: UiImage::new(icon),
                    ..default()
                });
            });
        // Insert the timer as a resource
        commands.insert_resource(SplashTimer(Timer::from_seconds(1.0, TimerMode::Once)));
    }

    // Tick the timer, and change state when finished
    fn countdown(
        mut game_state: ResMut<NextState<GameState>>,
        time: Res<Time>,
        mut timer: ResMut<SplashTimer>,
    ) {
        if timer.tick(time.delta()).finished() {
            game_state.set(GameState::Menu);
        }
    }
}

mod game {
    use bevy::{
        color::palettes::basic::{BLUE, LIME},
        prelude::*,
    };

    use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};

    // This plugin will contain the game. In this case, it's just be a screen that will
    // display the current settings for 5 seconds before returning to the menu
    pub fn game_plugin(app: &mut App) {
        app.add_systems(OnEnter(GameState::Game), game_setup)
            .add_systems(Update, game.run_if(in_state(GameState::Game)))
            .add_systems(OnExit(GameState::Game), despawn_screen::<OnGameScreen>);
    }

    // Tag component used to tag entities added on the game screen
    #[derive(Component)]
    struct OnGameScreen;

    #[derive(Resource, Deref, DerefMut)]
    struct GameTimer(Timer);

    fn game_setup(
        mut commands: Commands,
        display_quality: Res<DisplayQuality>,
        volume: Res<Volume>,
    ) {
        commands
            .spawn((
                NodeBundle {
                    style: Style {
                        width: Val::Percent(100.0),
                        height: Val::Percent(100.0),
                        // center children
                        align_items: AlignItems::Center,
                        justify_content: JustifyContent::Center,
                        ..default()
                    },
                    ..default()
                },
                OnGameScreen,
            ))
            .with_children(|parent| {
                // First create a `NodeBundle` for centering what we want to display
                parent
                    .spawn(NodeBundle {
                        style: Style {
                            // This will display its children in a column, from top to bottom
                            flex_direction: FlexDirection::Column,
                            // `align_items` will align children on the cross axis. Here the main axis is
                            // vertical (column), so the cross axis is horizontal. This will center the
                            // children
                            align_items: AlignItems::Center,
                            ..default()
                        },
                        background_color: Color::BLACK.into(),
                        ..default()
                    })
                    .with_children(|parent| {
                        // Display two lines of text, the second one with the current settings
                        parent.spawn(
                            TextBundle::from_section(
                                "Will be back to the menu shortly...",
                                TextStyle {
                                    font_size: 80.0,
                                    color: TEXT_COLOR,
                                    ..default()
                                },
                            )
                            .with_style(Style {
                                margin: UiRect::all(Val::Px(50.0)),
                                ..default()
                            }),
                        );
                        parent.spawn(
                            TextBundle::from_sections([
                                TextSection::new(
                                    format!("quality: {:?}", *display_quality),
                                    TextStyle {
                                        font_size: 60.0,
                                        color: BLUE.into(),
                                        ..default()
                                    },
                                ),
                                TextSection::new(
                                    " - ",
                                    TextStyle {
                                        font_size: 60.0,
                                        color: TEXT_COLOR,
                                        ..default()
                                    },
                                ),
                                TextSection::new(
                                    format!("volume: {:?}", *volume),
                                    TextStyle {
                                        font_size: 60.0,
                                        color: LIME.into(),
                                        ..default()
                                    },
                                ),
                            ])
                            .with_style(Style {
                                margin: UiRect::all(Val::Px(50.0)),
                                ..default()
                            }),
                        );
                    });
            });
        // Spawn a 5 seconds timer to trigger going back to the menu
        commands.insert_resource(GameTimer(Timer::from_seconds(5.0, TimerMode::Once)));
    }

    // Tick the timer, and change state when finished
    fn game(
        time: Res<Time>,
        mut game_state: ResMut<NextState<GameState>>,
        mut timer: ResMut<GameTimer>,
    ) {
        if timer.tick(time.delta()).finished() {
            game_state.set(GameState::Menu);
        }
    }
}

mod menu {
    use bevy::{app::AppExit, color::palettes::css::CRIMSON, prelude::*};

    use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};

    // This plugin manages the menu, with 5 different screens:
    // - a main menu with "New Game", "Settings", "Quit"
    // - a settings menu with two submenus and a back button
    // - two settings screen with a setting that can be set and a back button
    pub fn menu_plugin(app: &mut App) {
        app
            // At start, the menu is not enabled. This will be changed in `menu_setup` when
            // entering the `GameState::Menu` state.
            // Current screen in the menu is handled by an independent state from `GameState`
            .init_state::<MenuState>()
            .add_systems(OnEnter(GameState::Menu), menu_setup)
            // Systems to handle the main menu screen
            .add_systems(OnEnter(MenuState::Main), main_menu_setup)
            .add_systems(OnExit(MenuState::Main), despawn_screen::<OnMainMenuScreen>)
            // Systems to handle the settings menu screen
            .add_systems(OnEnter(MenuState::Settings), settings_menu_setup)
            .add_systems(
                OnExit(MenuState::Settings),
                despawn_screen::<OnSettingsMenuScreen>,
            )
            // Systems to handle the display settings screen
            .add_systems(
                OnEnter(MenuState::SettingsDisplay),
                display_settings_menu_setup,
            )
            .add_systems(
                Update,
                (setting_button::<DisplayQuality>.run_if(in_state(MenuState::SettingsDisplay)),),
            )
            .add_systems(
                OnExit(MenuState::SettingsDisplay),
                despawn_screen::<OnDisplaySettingsMenuScreen>,
            )
            // Systems to handle the sound settings screen
            .add_systems(OnEnter(MenuState::SettingsSound), sound_settings_menu_setup)
            .add_systems(
                Update,
                setting_button::<Volume>.run_if(in_state(MenuState::SettingsSound)),
            )
            .add_systems(
                OnExit(MenuState::SettingsSound),
                despawn_screen::<OnSoundSettingsMenuScreen>,
            )
            // Common systems to all screens that handles buttons behavior
            .add_systems(
                Update,
                (menu_action, button_system).run_if(in_state(GameState::Menu)),
            );
    }
examples/ecs/generic_system.rs (line 36)
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .init_state::<AppState>()
        .add_systems(Startup, setup_system)
        .add_systems(
            Update,
            (
                print_text_system,
                transition_to_in_game_system.run_if(in_state(AppState::MainMenu)),
            ),
        )
        // Cleanup systems.
        // Pass in the types your system should operate on using the ::<T> (turbofish) syntax
        .add_systems(OnExit(AppState::MainMenu), cleanup_system::<MenuClose>)
        .add_systems(OnExit(AppState::InGame), cleanup_system::<LevelUnload>)
        .run();
}
examples/2d/bounding_2d.rs (line 8)
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .init_state::<Test>()
        .add_systems(Startup, setup)
        .add_systems(
            Update,
            (update_text, spin, update_volumes, update_test_state),
        )
        .add_systems(
            PostUpdate,
            (
                render_shapes,
                (
                    aabb_intersection_system.run_if(in_state(Test::AabbSweep)),
                    circle_intersection_system.run_if(in_state(Test::CircleSweep)),
                    ray_cast_system.run_if(in_state(Test::RayCast)),
                    aabb_cast_system.run_if(in_state(Test::AabbCast)),
                    bounding_circle_cast_system.run_if(in_state(Test::CircleCast)),
                ),
                render_volumes,
            )
                .chain(),
        )
        .run();
}
examples/games/alien_cake_addict.rs (line 27)
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .init_resource::<Game>()
        .insert_resource(BonusSpawnTimer(Timer::from_seconds(
            5.0,
            TimerMode::Repeating,
        )))
        .init_state::<GameState>()
        .add_systems(Startup, setup_cameras)
        .add_systems(OnEnter(GameState::Playing), setup)
        .add_systems(
            Update,
            (
                move_player,
                focus_camera,
                rotate_bonus,
                scoreboard_system,
                spawn_bonus,
            )
                .run_if(in_state(GameState::Playing)),
        )
        .add_systems(OnExit(GameState::Playing), teardown)
        .add_systems(OnEnter(GameState::GameOver), display_score)
        .add_systems(
            Update,
            gameover_keyboard.run_if(in_state(GameState::GameOver)),
        )
        .add_systems(OnExit(GameState::GameOver), teardown)
        .run();
}
examples/ecs/state.rs (line 13)
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .init_state::<AppState>() // Alternatively we could use .insert_state(AppState::Menu)
        .add_systems(Startup, setup)
        // This system runs when we enter `AppState::Menu`, during the `StateTransition` schedule.
        // All systems from the exit schedule of the state we're leaving are run first,
        // and then all systems from the enter schedule of the state we're entering are run second.
        .add_systems(OnEnter(AppState::Menu), setup_menu)
        // By contrast, update systems are stored in the `Update` schedule. They simply
        // check the value of the `State<T>` resource to see if they should run each frame.
        .add_systems(Update, menu.run_if(in_state(AppState::Menu)))
        .add_systems(OnExit(AppState::Menu), cleanup_menu)
        .add_systems(OnEnter(AppState::InGame), setup_game)
        .add_systems(
            Update,
            (movement, change_color).run_if(in_state(AppState::InGame)),
        )
        .add_systems(Update, log_transitions)
        .run();
}

pub fn insert_state<S>(&mut self, state: S) -> &mut App
where S: States,

Inserts a specific State to the current App and overrides any State previously added of the same type.

Adds State<S> and NextState<S> resources, OnEnter and OnExit schedules for each state variant (if they don’t already exist), an instance of apply_state_transition::<S> in StateTransition so that transitions happen before Update and an instance of run_enter_schedule::<S> in StateTransition with a run_once condition to run the on enter schedule of the initial state.

If you would like to control how other systems run based on the current state, you can emulate this behavior using the in_state Condition.

Note that you can also apply state transitions at other points in the schedule by adding the apply_state_transition::<S> system manually.

pub fn add_systems<M>( &mut self, schedule: impl ScheduleLabel, systems: impl IntoSystemConfigs<M> ) -> &mut App

Adds a collection of systems to schedule (stored in the main world’s Schedules).

§Examples
app.add_systems(Update, (system_a, system_b, system_c));
app.add_systems(Update, (system_a, system_b).run_if(should_run));
Examples found in repository?
examples/hello_world.rs (line 6)
5
6
7
fn main() {
    App::new().add_systems(Update, hello_world_system).run();
}
More examples
Hide additional examples
examples/app/plugin_group.rs (line 41)
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
    fn build(&self, app: &mut App) {
        app.add_systems(Update, print_hello_system);
    }
}

fn print_hello_system() {
    info!("hello");
}

struct PrintWorldPlugin;

impl Plugin for PrintWorldPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(Update, print_world_system);
    }
examples/3d/../helpers/camera_controller.rs (line 15)
14
15
16
    fn build(&self, app: &mut App) {
        app.add_systems(Update, run_camera_controller);
    }
examples/tools/scene_viewer/animation_plugin.rs (line 194)
193
194
195
    fn build(&self, app: &mut App) {
        app.add_systems(Update, (handle_inputs, assign_clips));
    }
examples/2d/2d_shapes.rs (line 11)
8
9
10
11
12
13
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
examples/2d/mesh2d.rs (line 8)
5
6
7
8
9
10
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}

pub fn register_system<I, O, M, S>(&mut self, system: S) -> SystemId<I, O>
where I: 'static, O: 'static, S: IntoSystem<I, O, M> + 'static,

Registers a system and returns a SystemId so it can later be called by World::run_system.

It’s possible to register the same systems more than once, they’ll be stored separately.

This is different from adding systems to a Schedule with App::add_systems, because the SystemId that is returned can be used anywhere in the World to run the associated system. This allows for running systems in a push-based fashion. Using a Schedule is still preferred for most cases due to its better performance and ability to run non-conflicting systems simultaneously.

pub fn configure_sets( &mut self, schedule: impl ScheduleLabel, sets: impl IntoSystemSetConfigs ) -> &mut App

Configures a collection of system sets in the provided schedule, adding any sets that do not exist.

Examples found in repository?
examples/ecs/ecs_guide.rs (lines 288-292)
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
fn main() {
    // Bevy apps are created using the builder pattern. We use the builder to add systems,
    // resources, and plugins to our app
    App::new()
        // Resources that implement the Default or FromWorld trait can be added like this:
        .init_resource::<GameState>()
        // Plugins are just a grouped set of app builder calls (just like we're doing here).
        // We could easily turn our game into a plugin, but you can check out the plugin example for
        // that :) The plugin below runs our app's "system schedule" once every 5 seconds.
        .add_plugins(ScheduleRunnerPlugin::run_loop(Duration::from_secs(5)))
        // `Startup` systems run exactly once BEFORE all other systems. These are generally used for
        // app initialization code (ex: adding entities and resources)
        .add_systems(Startup, startup_system)
        // `Update` systems run once every update. These are generally used for "real-time app logic"
        .add_systems(Update, print_message_system)
        // SYSTEM EXECUTION ORDER
        //
        // Each system belongs to a `Schedule`, which controls the execution strategy and broad order
        // of the systems within each tick. The `Startup` schedule holds
        // startup systems, which are run a single time before `Update` runs. `Update` runs once per app update,
        // which is generally one "frame" or one "tick".
        //
        // By default, all systems in a `Schedule` run in parallel, except when they require mutable access to a
        // piece of data. This is efficient, but sometimes order matters.
        // For example, we want our "game over" system to execute after all other systems to ensure
        // we don't accidentally run the game for an extra round.
        //
        // You can force an explicit ordering between systems using the `.before` or `.after` methods.
        // Systems will not be scheduled until all of the systems that they have an "ordering dependency" on have
        // completed.
        // There are other schedules, such as `Last` which runs at the very end of each run.
        .add_systems(Last, print_at_end_round)
        // We can also create new system sets, and order them relative to other system sets.
        // Here is what our games execution order will look like:
        // "before_round": new_player_system, new_round_system
        // "round": print_message_system, score_system
        // "after_round": score_check_system, game_over_system
        .configure_sets(
            Update,
            // chain() will ensure sets run in the order they are listed
            (MySet::BeforeRound, MySet::Round, MySet::AfterRound).chain(),
        )
        // The add_systems function is powerful. You can define complex system configurations with ease!
        .add_systems(
            Update,
            (
                // These `BeforeRound` systems will run before `Round` systems, thanks to the chained set configuration
                (
                    // You can also chain systems! new_round_system will run first, followed by new_player_system
                    (new_round_system, new_player_system).chain(),
                    exclusive_player_system,
                )
                    // All of the systems in the tuple above will be added to this set
                    .in_set(MySet::BeforeRound),
                // This `Round` system will run after the `BeforeRound` systems thanks to the chained set configuration
                score_system.in_set(MySet::Round),
                // These `AfterRound` systems will run after the `Round` systems thanks to the chained set configuration
                (
                    score_check_system,
                    // In addition to chain(), you can also use `before(system)` and `after(system)`. This also works
                    // with sets!
                    game_over_system.after(score_check_system),
                )
                    .in_set(MySet::AfterRound),
            ),
        )
        // This call to run() starts the app we just built!
        .run();
}

pub fn add_event<T>(&mut self) -> &mut App
where T: Event,

Initializes T event handling by inserting an event queue resource (Events::<T>) and scheduling an event_update_system in First.

See Events for information on how to define events.

§Examples
app.add_event::<MyEvent>();
Examples found in repository?
examples/audio/pitch.rs (line 9)
6
7
8
9
10
11
12
13
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_event::<PlayPitch>()
        .add_systems(Startup, setup)
        .add_systems(Update, (play_pitch, keyboard_input_system))
        .run();
}
More examples
Hide additional examples
examples/async_tasks/external_source_external_thread.rs (line 12)
10
11
12
13
14
15
16
17
fn main() {
    App::new()
        .add_event::<StreamEvent>()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, (read_stream, spawn_text, move_text))
        .run();
}
examples/ecs/component_hooks.rs (line 45)
39
40
41
42
43
44
45
46
47
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, trigger_hooks)
        .init_resource::<MyComponentIndex>()
        .add_event::<MyEvent>()
        .run();
}
examples/ui/size_constraints.rs (line 8)
5
6
7
8
9
10
11
12
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_event::<ButtonActivatedEvent>()
        .add_systems(Startup, setup)
        .add_systems(Update, (update_buttons, update_radio_buttons_colors))
        .run();
}
examples/ecs/event.rs (line 9)
6
7
8
9
10
11
12
13
14
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_event::<MyEvent>()
        .add_event::<PlaySound>()
        .init_resource::<EventTriggerState>()
        .add_systems(Update, (event_trigger, event_listener, sound_player))
        .run();
}
examples/app/log_layers_ecs.rs (line 87)
80
81
82
83
84
85
86
87
88
89
90
91
fn update_subscriber(app: &mut App, subscriber: BoxedSubscriber) -> BoxedSubscriber {
    let (sender, receiver) = mpsc::channel();

    let layer = CaptureLayer { sender };
    let resource = CapturedLogEvents(receiver);

    app.insert_non_send_resource(resource);
    app.add_event::<LogEvent>();
    app.add_systems(Update, transfer_log_events);

    Box::new(subscriber.with(layer))
}

pub fn insert_resource<R>(&mut self, resource: R) -> &mut App
where R: Resource,

Inserts the Resource into the app, overwriting any existing resource of the same type.

There is also an init_resource for resources that have Default or FromWorld implementations.

§Examples
#[derive(Resource)]
struct MyCounter {
    counter: usize,
}

App::new()
   .insert_resource(MyCounter { counter: 0 });
Examples found in repository?
examples/app/custom_loop.rs (line 27)
25
26
27
28
29
30
31
fn main() {
    App::new()
        .insert_resource(Input(String::new()))
        .set_runner(my_runner)
        .add_systems(Update, print_system)
        .run();
}
More examples
Hide additional examples
examples/ecs/system_param.rs (line 7)
5
6
7
8
9
10
11
fn main() {
    App::new()
        .insert_resource(PlayerCount(0))
        .add_systems(Startup, spawn)
        .add_systems(Update, count_players)
        .run();
}
examples/ui/transparency_ui.rs (line 8)
6
7
8
9
10
11
12
fn main() {
    App::new()
        .insert_resource(ClearColor(Color::BLACK))
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
examples/ui/z_index.rs (line 13)
11
12
13
14
15
16
17
fn main() {
    App::new()
        .insert_resource(ClearColor(Color::BLACK))
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
examples/shader/gpu_readback.rs (line 41)
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
fn main() {
    App::new()
        .insert_resource(ClearColor(Color::BLACK))
        .add_plugins((DefaultPlugins, GpuReadbackPlugin))
        .add_systems(Update, receive)
        .run();
}

/// This system will poll the channel and try to get the data sent from the render world
fn receive(receiver: Res<MainWorldReceiver>) {
    // We don't want to block the main world on this,
    // so we use try_recv which attempts to receive without blocking
    if let Ok(data) = receiver.try_recv() {
        println!("Received data from render world: {data:?}");
    }
}

// We need a plugin to organize all the systems and render node required for this example
struct GpuReadbackPlugin;
impl Plugin for GpuReadbackPlugin {
    fn build(&self, _app: &mut App) {}

    // The render device is only accessible inside finish().
    // So we need to initialize render resources here.
    fn finish(&self, app: &mut App) {
        let (s, r) = crossbeam_channel::unbounded();
        app.insert_resource(MainWorldReceiver(r));

        let render_app = app.sub_app_mut(RenderApp);
        render_app
            .insert_resource(RenderWorldSender(s))
            .init_resource::<ComputePipeline>()
            .init_resource::<Buffers>()
            .add_systems(
                Render,
                (
                    prepare_bind_group
                        .in_set(RenderSet::PrepareBindGroups)
                        // We don't need to recreate the bind group every frame
                        .run_if(not(resource_exists::<GpuBufferBindGroup>)),
                    // We need to run it after the render graph is done
                    // because this needs to happen after submit()
                    map_and_read_buffer.after(RenderSet::Render),
                ),
            );

        // Add the compute node as a top level node to the render graph
        // This means it will only execute once per frame
        render_app
            .world_mut()
            .resource_mut::<RenderGraph>()
            .add_node(ComputeNodeLabel, ComputeNode::default());
    }
examples/3d/transparency_3d.rs (line 9)
7
8
9
10
11
12
13
14
fn main() {
    App::new()
        .insert_resource(Msaa::default())
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, fade_transparency)
        .run();
}

pub fn init_resource<R>(&mut self) -> &mut App
where R: Resource + FromWorld,

Inserts the Resource, initialized with its default value, into the app, if there is no existing instance of R.

R must implement FromWorld. If R implements Default, FromWorld will be automatically implemented and initialize the Resource with Default::default.

§Examples
#[derive(Resource)]
struct MyCounter {
    counter: usize,
}

impl Default for MyCounter {
    fn default() -> MyCounter {
        MyCounter {
            counter: 100
        }
    }
}

App::new()
    .init_resource::<MyCounter>();
Examples found in repository?
examples/time/timers.rs (line 8)
5
6
7
8
9
10
11
12
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .init_resource::<Countdown>()
        .add_systems(Startup, setup)
        .add_systems(Update, (countdown, print_when_completed))
        .run();
}
More examples
Hide additional examples
examples/ecs/component_hooks.rs (line 44)
39
40
41
42
43
44
45
46
47
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, trigger_hooks)
        .init_resource::<MyComponentIndex>()
        .add_event::<MyEvent>()
        .run();
}
examples/games/contributors.rs (line 15)
12
13
14
15
16
17
18
19
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .init_resource::<SelectionTimer>()
        .add_systems(Startup, (setup_contributor_selection, setup))
        .add_systems(Update, (gravity, movement, collisions, selection))
        .run();
}
examples/ecs/event.rs (line 11)
6
7
8
9
10
11
12
13
14
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_event::<MyEvent>()
        .add_event::<PlaySound>()
        .init_resource::<EventTriggerState>()
        .add_systems(Update, (event_trigger, event_listener, sound_player))
        .run();
}
examples/ui/font_atlas_debug.rs (line 10)
8
9
10
11
12
13
14
15
16
fn main() {
    App::new()
        .init_resource::<State>()
        .insert_resource(ClearColor(Color::BLACK))
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, (text_update_system, atlas_render_system))
        .run();
}
examples/asset/custom_asset.rs (line 92)
89
90
91
92
93
94
95
96
97
98
99
100
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .init_resource::<State>()
        .init_asset::<CustomAsset>()
        .init_asset::<Blob>()
        .init_asset_loader::<CustomAssetLoader>()
        .init_asset_loader::<BlobAssetLoader>()
        .add_systems(Startup, setup)
        .add_systems(Update, print_on_load)
        .run();
}

pub fn insert_non_send_resource<R>(&mut self, resource: R) -> &mut App
where R: 'static,

Inserts the !Send resource into the app, overwriting any existing resource of the same type.

There is also an init_non_send_resource for resources that implement Default

§Examples
struct MyCounter {
    counter: usize,
}

App::new()
    .insert_non_send_resource(MyCounter { counter: 0 });
Examples found in repository?
examples/app/log_layers_ecs.rs (line 86)
80
81
82
83
84
85
86
87
88
89
90
91
fn update_subscriber(app: &mut App, subscriber: BoxedSubscriber) -> BoxedSubscriber {
    let (sender, receiver) = mpsc::channel();

    let layer = CaptureLayer { sender };
    let resource = CapturedLogEvents(receiver);

    app.insert_non_send_resource(resource);
    app.add_event::<LogEvent>();
    app.add_systems(Update, transfer_log_events);

    Box::new(subscriber.with(layer))
}

pub fn init_non_send_resource<R>(&mut self) -> &mut App
where R: 'static + Default,

Inserts the !Send resource into the app, initialized with its default value, if there is no existing instance of R.

pub fn is_plugin_added<T>(&self) -> bool
where T: Plugin,

Returns true if the Plugin has already been added.

pub fn get_added_plugins<T>(&self) -> Vec<&T>
where T: Plugin,

Returns a vector of references to all plugins of type T that have been added.

This can be used to read the settings of any existing plugins. This vector will be empty if no plugins of that type have been added. If multiple copies of the same plugin are added to the App, they will be listed in insertion order in this vector.

let default_sampler = app.get_added_plugins::<ImagePlugin>()[0].default_sampler;

pub fn add_plugins<M>(&mut self, plugins: impl Plugins<M>) -> &mut App

Installs a Plugin collection.

Bevy prioritizes modularity as a core principle. All engine features are implemented as plugins, even the complex ones like rendering.

Plugins can be grouped into a set by using a PluginGroup.

There are built-in PluginGroups that provide core engine functionality. The PluginGroups available by default are DefaultPlugins and MinimalPlugins.

To customize the plugins in the group (reorder, disable a plugin, add a new plugin before / after another plugin), call build() on the group, which will convert it to a PluginGroupBuilder.

You can also specify a group of Plugins by using a tuple over Plugins and PluginGroups. See Plugins for more details.

§Examples
App::new()
    .add_plugins(MinimalPlugins);
App::new()
    .add_plugins((MinimalPlugins, LogPlugin));
§Panics

Panics if one of the plugins had already been added to the application.

Examples found in repository?
examples/app/empty_defaults.rs (line 6)
5
6
7
fn main() {
    App::new().add_plugins(DefaultPlugins).run();
}
More examples
Hide additional examples
examples/2d/2d_shapes.rs (line 10)
8
9
10
11
12
13
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
examples/2d/mesh2d.rs (line 7)
5
6
7
8
9
10
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
examples/2d/mesh2d_vertex_color_texture.rs (line 11)
9
10
11
12
13
14
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
examples/2d/sprite.rs (line 7)
5
6
7
8
9
10
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
examples/2d/sprite_flipping.rs (line 7)
5
6
7
8
9
10
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}

pub fn register_type<T>(&mut self) -> &mut App

Available on crate feature bevy_reflect only.

Registers the type T in the TypeRegistry resource, adding reflect data as specified in the Reflect derive:

#[derive(Component, Serialize, Deserialize, Reflect)]
#[reflect(Component, Serialize, Deserialize)] // will register ReflectComponent, ReflectSerialize, ReflectDeserialize

See bevy_reflect::TypeRegistry::register for more information.

Examples found in repository?
examples/reflection/trait_reflection.rs (line 8)
5
6
7
8
9
10
11
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .register_type::<MyType>()
        .add_systems(Startup, setup)
        .run();
}
More examples
Hide additional examples
examples/reflection/reflection.rs (line 20)
16
17
18
19
20
21
22
23
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        // Bar will be automatically registered as it's a dependency of Foo
        .register_type::<Foo>()
        .add_systems(Startup, setup)
        .run();
}
examples/reflection/generic_reflection.rs (line 10)
6
7
8
9
10
11
12
13
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        // You must manually register each instance of a generic type
        .register_type::<MyType<u32>>()
        .add_systems(Startup, setup)
        .run();
}
examples/scene/scene.rs (line 8)
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .register_type::<ComponentA>()
        .register_type::<ComponentB>()
        .register_type::<ResourceA>()
        .add_systems(
            Startup,
            (save_scene_system, load_scene_system, infotext_system),
        )
        .add_systems(Update, log_system)
        .run();
}

pub fn register_type_data<T, D>(&mut self) -> &mut App
where T: Reflect + TypePath, D: TypeData + FromType<T>,

Available on crate feature bevy_reflect only.

Associates type data D with type T in the TypeRegistry resource.

Most of the time register_type can be used instead to register a type you derived Reflect for. However, in cases where you want to add a piece of type data that was not included in the list of #[reflect(...)] type data in the derive, or where the type is generic and cannot register e.g. ReflectSerialize unconditionally without knowing the specific type parameters, this method can be used to insert additional type data.

§Example
use bevy_app::App;
use bevy_reflect::{ReflectSerialize, ReflectDeserialize};

App::new()
    .register_type::<Option<String>>()
    .register_type_data::<Option<String>, ReflectSerialize>()
    .register_type_data::<Option<String>, ReflectDeserialize>();

See bevy_reflect::TypeRegistry::register_type_data.

pub fn world(&self) -> &World

Returns a reference to the World.

pub fn world_mut(&mut self) -> &mut World

Returns a mutable reference to the World.

Examples found in repository?
examples/app/custom_loop.rs (line 14)
10
11
12
13
14
15
16
17
18
19
fn my_runner(mut app: App) {
    println!("Type stuff into the console");
    for line in io::stdin().lines() {
        {
            let mut input = app.world_mut().resource_mut::<Input>();
            input.0 = line.unwrap();
        }
        app.update();
    }
}
More examples
Hide additional examples
examples/2d/mesh2d_manual.rs (line 288)
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
    fn build(&self, app: &mut App) {
        // Load our custom shader
        let mut shaders = app.world_mut().resource_mut::<Assets<Shader>>();
        shaders.insert(
            &COLORED_MESH2D_SHADER_HANDLE,
            Shader::from_wgsl(COLORED_MESH2D_SHADER, file!()),
        );

        // Register our custom draw function, and add our render systems
        app.get_sub_app_mut(RenderApp)
            .unwrap()
            .add_render_command::<Transparent2d, DrawColoredMesh2d>()
            .init_resource::<SpecializedRenderPipelines<ColoredMesh2dPipeline>>()
            .add_systems(
                ExtractSchedule,
                extract_colored_mesh2d.after(extract_mesh2d),
            )
            .add_systems(Render, queue_colored_mesh2d.in_set(RenderSet::QueueMeshes));
    }
examples/games/stepping.rs (line 44)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
    fn build(&self, app: &mut App) {
        app.add_systems(Startup, build_stepping_hint);
        if cfg!(not(feature = "bevy_debug_stepping")) {
            return;
        }

        // create and insert our debug schedule into the main schedule order.
        // We need an independent schedule so we have access to all other
        // schedules through the `Stepping` resource
        app.init_schedule(DebugSchedule);
        let mut order = app.world_mut().resource_mut::<MainScheduleOrder>();
        order.insert_after(Update, DebugSchedule);

        // create our stepping resource
        let mut stepping = Stepping::new();
        for label in &self.schedule_labels {
            stepping.add_schedule(*label);
        }
        app.insert_resource(stepping);

        // add our startup & stepping systems
        app.insert_resource(State {
            ui_top: self.top,
            ui_left: self.left,
            systems: Vec::new(),
        })
        .add_systems(
            DebugSchedule,
            (
                build_ui.run_if(not(initialized)),
                handle_input,
                update_ui.run_if(initialized),
            )
                .chain(),
        );
    }
examples/time/time.rs (line 48)
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
fn runner(mut app: App) {
    banner();
    help();
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        if let Err(err) = line {
            println!("read err: {:#}", err);
            break;
        }
        match line.unwrap().as_str() {
            "" => {
                app.update();
            }
            "f" => {
                println!("FAST: setting relative speed to 2x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(2.0);
            }
            "n" => {
                println!("NORMAL: setting relative speed to 1x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(1.0);
            }
            "s" => {
                println!("SLOW: setting relative speed to 0.5x");
                app.world_mut()
                    .resource_mut::<Time<Virtual>>()
                    .set_relative_speed(0.5);
            }
            "p" => {
                println!("PAUSE: pausing virtual clock");
                app.world_mut().resource_mut::<Time<Virtual>>().pause();
            }
            "u" => {
                println!("UNPAUSE: resuming virtual clock");
                app.world_mut().resource_mut::<Time<Virtual>>().unpause();
            }
            "q" => {
                println!("QUITTING!");
                break;
            }
            _ => {
                help();
            }
        }
    }
}
examples/ecs/custom_schedule.rs (line 36)
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
fn main() {
    let mut app = App::new();

    // Create a new [`Schedule`]. For demonstration purposes, we configure it to use a single threaded executor so that
    // systems in this schedule are never run in parallel. However, this is not a requirement for custom schedules in
    // general.
    let mut custom_update_schedule = Schedule::new(SingleThreadedUpdate);
    custom_update_schedule.set_executor_kind(ExecutorKind::SingleThreaded);

    // Adding the schedule to the app does not automatically run the schedule. This merely registers the schedule so
    // that systems can look it up using the `Schedules` resource.
    app.add_schedule(custom_update_schedule);

    // Bevy `App`s have a `main_schedule_label` field that configures which schedule is run by the App's `runner`.
    // By default, this is `Main`. The `Main` schedule is responsible for running Bevy's main schedules such as
    // `Update`, `Startup` or `Last`.
    //
    // We can configure the `Main` schedule to run our custom update schedule relative to the existing ones by modifying
    // the `MainScheduleOrder` resource.
    //
    // Note that we modify `MainScheduleOrder` directly in `main` and not in a startup system. The reason for this is
    // that the `MainScheduleOrder` cannot be modified from systems that are run as part of the `Main` schedule.
    let mut main_schedule_order = app.world_mut().resource_mut::<MainScheduleOrder>();
    main_schedule_order.insert_after(Update, SingleThreadedUpdate);

    // Adding a custom startup schedule works similarly, but needs to use `insert_startup_after`
    // instead of `insert_after`.
    app.add_schedule(Schedule::new(CustomStartup));

    let mut main_schedule_order = app.world_mut().resource_mut::<MainScheduleOrder>();
    main_schedule_order.insert_startup_after(PreStartup, CustomStartup);

    app.add_systems(SingleThreadedUpdate, single_threaded_update_system)
        .add_systems(CustomStartup, custom_startup_system)
        .add_systems(PreStartup, pre_startup_system)
        .add_systems(Startup, startup_system)
        .add_systems(First, first_system)
        .add_systems(Update, update_system)
        .add_systems(Last, last_system)
        .run();
}
examples/ecs/system_stepping.rs (line 59)
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
fn main() {
    let mut app = App::new();

    app
        // to display log messages from Stepping resource
        .add_plugins(LogPlugin::default())
        .add_systems(
            Update,
            (
                update_system_one,
                // establish a dependency here to simplify descriptions below
                update_system_two.after(update_system_one),
                update_system_three.after(update_system_two),
                update_system_four,
            ),
        )
        .add_systems(PreUpdate, pre_update_system);

    // For the simplicity of this example, we directly modify the `Stepping`
    // resource here and run the systems with `App::update()`.  Each call to
    // `App::update()` is the equivalent of a single frame render when using
    // `App::run()`.
    //
    // In a real-world situation, the `Stepping` resource would be modified by
    // a system based on input from the user.  A full demonstration of this can
    // be found in the breakout example.
    println!(
        r#"
    Actions: call app.update()
     Result: All systems run normally"#
    );
    app.update();

    println!(
        r#"
    Actions: Add the Stepping resource then call app.update()
     Result: All systems run normally.  Stepping has no effect unless explicitly
             configured for a Schedule, and Stepping has been enabled."#
    );
    app.insert_resource(Stepping::new());
    app.update();

    println!(
        r#"
    Actions: Add the Update Schedule to Stepping; enable Stepping; call
             app.update()
     Result: Only the systems in PreUpdate run.  When Stepping is enabled,
             systems in the configured schedules will not run unless:
             * Stepping::step_frame() is called
             * Stepping::continue_frame() is called
             * System has been configured to always run"#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.add_schedule(Update).enable();
    app.update();

    println!(
        r#"
    Actions: call Stepping.step_frame(); call app.update()
     Result: The PreUpdate systems run, and one Update system will run.  In
             Stepping, step means run the next system across all the schedules 
             that have been added to the Stepping resource."#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.step_frame();
    app.update();

    println!(
        r#"
    Actions: call app.update()
     Result: Only the PreUpdate systems run.  The previous call to
             Stepping::step_frame() only applies for the next call to
             app.update()/the next frame rendered.
    "#
    );
    app.update();

    println!(
        r#"
    Actions: call Stepping::continue_frame(); call app.update()
     Result: PreUpdate system will run, and all remaining Update systems will
             run.  Stepping::continue_frame() tells stepping to run all systems
             starting after the last run system until it hits the end of the
             frame, or it encounters a system with a breakpoint set.  In this
             case, we previously performed a step, running one system in Update.
             This continue will cause all remaining systems in Update to run."#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.continue_frame();
    app.update();

    println!(
        r#"
    Actions: call Stepping::step_frame() & app.update() four times in a row
     Result: PreUpdate system runs every time we call app.update(), along with
             one system from the Update schedule each time.  This shows what
             execution would look like to step through an entire frame of 
             systems."#
    );
    for _ in 0..4 {
        let mut stepping = app.world_mut().resource_mut::<Stepping>();
        stepping.step_frame();
        app.update();
    }

    println!(
        r#"
    Actions: Stepping::always_run(Update, update_system_two); step through all
             systems
     Result: PreUpdate system and update_system_two() will run every time we
             call app.update().  We'll also only need to step three times to
             execute all systems in the frame.  Stepping::always_run() allows
             us to granularly allow systems to run when stepping is enabled."#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.always_run(Update, update_system_two);
    for _ in 0..3 {
        let mut stepping = app.world_mut().resource_mut::<Stepping>();
        stepping.step_frame();
        app.update();
    }

    println!(
        r#"
    Actions: Stepping::never_run(Update, update_system_two); continue through
             all systems
     Result: All systems except update_system_two() will execute.
             Stepping::never_run() allows us to disable systems while Stepping
             is enabled."#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.never_run(Update, update_system_two);
    stepping.continue_frame();
    app.update();

    println!(
        r#"
    Actions: Stepping::set_breakpoint(Update, update_system_two); continue,
             step, continue
     Result: During the first continue, pre_update_system() and
             update_system_one() will run.  update_system_four() may also run
             as it has no dependency on update_system_two() or
             update_system_three().  Nether update_system_two() nor
             update_system_three() will run in the first app.update() call as
             they form a chained dependency on update_system_one() and run
             in order of one, two, three.  Stepping stops system execution in
             the Update schedule when it encounters the breakpoint for
             update_system_three().
             During the step we run update_system_two() along with the
             pre_update_system().
             During the final continue pre_update_system() and
             update_system_three() run."#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.set_breakpoint(Update, update_system_two);
    stepping.continue_frame();
    app.update();
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.step_frame();
    app.update();
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.continue_frame();
    app.update();

    println!(
        r#"
    Actions: Stepping::clear_breakpoint(Update, update_system_two); continue
             through all systems
     Result: All systems will run"#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.clear_breakpoint(Update, update_system_two);
    stepping.continue_frame();
    app.update();

    println!(
        r#"
    Actions: Stepping::disable(); app.update()
     Result: All systems will run.  With Stepping disabled, there's no need to
             call Stepping::step_frame() or Stepping::continue_frame() to run
             systems in the Update schedule."#
    );
    let mut stepping = app.world_mut().resource_mut::<Stepping>();
    stepping.disable();
    app.update();
}

pub fn main(&self) -> &SubApp

Returns a reference to the main SubApp.

pub fn main_mut(&mut self) -> &mut SubApp

Returns a mutable reference to the main SubApp.

pub fn sub_app(&self, label: impl AppLabel) -> &SubApp

Returns a reference to the SubApp with the given label.

§Panics

Panics if the SubApp doesn’t exist.

pub fn sub_app_mut(&mut self, label: impl AppLabel) -> &mut SubApp

Returns a reference to the SubApp with the given label.

§Panics

Panics if the SubApp doesn’t exist.

Examples found in repository?
examples/shader/shader_instancing.rs (line 85)
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
    fn build(&self, app: &mut App) {
        app.add_plugins(ExtractComponentPlugin::<InstanceMaterialData>::default());
        app.sub_app_mut(RenderApp)
            .add_render_command::<Transparent3d, DrawCustom>()
            .init_resource::<SpecializedMeshPipelines<CustomPipeline>>()
            .add_systems(
                Render,
                (
                    queue_custom.in_set(RenderSet::QueueMeshes),
                    prepare_instance_buffers.in_set(RenderSet::PrepareResources),
                ),
            );
    }

    fn finish(&self, app: &mut App) {
        app.sub_app_mut(RenderApp).init_resource::<CustomPipeline>();
    }
More examples
Hide additional examples
examples/games/loading_screen.rs (line 334)
326
327
328
329
330
331
332
333
334
335
336
        fn build(&self, app: &mut App) {
            app.insert_resource(PipelinesReady::default());

            // In order to gain access to the pipelines status, we have to
            // go into the `RenderApp`, grab the resource from the main App
            // and then update the pipelines status from there.
            // Writing between these Apps can only be done through the
            // `ExtractSchedule`.
            app.sub_app_mut(bevy::render::RenderApp)
                .add_systems(ExtractSchedule, update_pipelines_ready);
        }
examples/shader/compute_shader_game_of_life.rs (line 104)
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    fn build(&self, app: &mut App) {
        // Extract the game of life image resource from the main world into the render world
        // for operation on by the compute shader and display on the sprite.
        app.add_plugins(ExtractResourcePlugin::<GameOfLifeImages>::default());
        let render_app = app.sub_app_mut(RenderApp);
        render_app.add_systems(
            Render,
            prepare_bind_group.in_set(RenderSet::PrepareBindGroups),
        );

        let mut render_graph = render_app.world_mut().resource_mut::<RenderGraph>();
        render_graph.add_node(GameOfLifeLabel, GameOfLifeNode::default());
        render_graph.add_node_edge(GameOfLifeLabel, bevy::render::graph::CameraDriverLabel);
    }

    fn finish(&self, app: &mut App) {
        let render_app = app.sub_app_mut(RenderApp);
        render_app.init_resource::<GameOfLifePipeline>();
    }
examples/shader/gpu_readback.rs (line 67)
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
    fn finish(&self, app: &mut App) {
        let (s, r) = crossbeam_channel::unbounded();
        app.insert_resource(MainWorldReceiver(r));

        let render_app = app.sub_app_mut(RenderApp);
        render_app
            .insert_resource(RenderWorldSender(s))
            .init_resource::<ComputePipeline>()
            .init_resource::<Buffers>()
            .add_systems(
                Render,
                (
                    prepare_bind_group
                        .in_set(RenderSet::PrepareBindGroups)
                        // We don't need to recreate the bind group every frame
                        .run_if(not(resource_exists::<GpuBufferBindGroup>)),
                    // We need to run it after the render graph is done
                    // because this needs to happen after submit()
                    map_and_read_buffer.after(RenderSet::Render),
                ),
            );

        // Add the compute node as a top level node to the render graph
        // This means it will only execute once per frame
        render_app
            .world_mut()
            .resource_mut::<RenderGraph>()
            .add_node(ComputeNodeLabel, ComputeNode::default());
    }

pub fn get_sub_app(&self, label: impl AppLabel) -> Option<&SubApp>

Returns a reference to the SubApp with the given label, if it exists.

pub fn get_sub_app_mut(&mut self, label: impl AppLabel) -> Option<&mut SubApp>

Returns a mutable reference to the SubApp with the given label, if it exists.

Examples found in repository?
examples/stress_tests/many_lights.rs (line 160)
159
160
161
162
163
164
165
    fn build(&self, app: &mut App) {
        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
            return;
        };

        render_app.add_systems(Render, print_visible_light_count.in_set(RenderSet::Prepare));
    }
More examples
Hide additional examples
examples/shader/texture_binding_array.rs (line 39)
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
    fn finish(&self, app: &mut App) {
        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
            return;
        };

        let render_device = render_app.world().resource::<RenderDevice>();

        // Check if the device support the required feature. If not, exit the example.
        // In a real application, you should setup a fallback for the missing feature
        if !render_device
            .features()
            .contains(WgpuFeatures::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING)
        {
            error!(
                "Render device doesn't support feature \
SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING, \
which is required for texture binding arrays"
            );
            exit(1);
        }
    }
examples/2d/mesh2d_manual.rs (line 295)
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
    fn build(&self, app: &mut App) {
        // Load our custom shader
        let mut shaders = app.world_mut().resource_mut::<Assets<Shader>>();
        shaders.insert(
            &COLORED_MESH2D_SHADER_HANDLE,
            Shader::from_wgsl(COLORED_MESH2D_SHADER, file!()),
        );

        // Register our custom draw function, and add our render systems
        app.get_sub_app_mut(RenderApp)
            .unwrap()
            .add_render_command::<Transparent2d, DrawColoredMesh2d>()
            .init_resource::<SpecializedRenderPipelines<ColoredMesh2dPipeline>>()
            .add_systems(
                ExtractSchedule,
                extract_colored_mesh2d.after(extract_mesh2d),
            )
            .add_systems(Render, queue_colored_mesh2d.in_set(RenderSet::QueueMeshes));
    }

    fn finish(&self, app: &mut App) {
        // Register our custom pipeline
        app.get_sub_app_mut(RenderApp)
            .unwrap()
            .init_resource::<ColoredMesh2dPipeline>();
    }
examples/shader/post_processing.rs (line 62)
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
    fn build(&self, app: &mut App) {
        app.add_plugins((
            // The settings will be a component that lives in the main world but will
            // be extracted to the render world every frame.
            // This makes it possible to control the effect from the main world.
            // This plugin will take care of extracting it automatically.
            // It's important to derive [`ExtractComponent`] on [`PostProcessingSettings`]
            // for this plugin to work correctly.
            ExtractComponentPlugin::<PostProcessSettings>::default(),
            // The settings will also be the data used in the shader.
            // This plugin will prepare the component for the GPU by creating a uniform buffer
            // and writing the data to that buffer every frame.
            UniformComponentPlugin::<PostProcessSettings>::default(),
        ));

        // We need to get the render app from the main app
        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
            return;
        };

        render_app
            // Bevy's renderer uses a render graph which is a collection of nodes in a directed acyclic graph.
            // It currently runs on each view/camera and executes each node in the specified order.
            // It will make sure that any node that needs a dependency from another node
            // only runs when that dependency is done.
            //
            // Each node can execute arbitrary work, but it generally runs at least one render pass.
            // A node only has access to the render world, so if you need data from the main world
            // you need to extract it manually or with the plugin like above.
            // Add a [`Node`] to the [`RenderGraph`]
            // The Node needs to impl FromWorld
            //
            // The [`ViewNodeRunner`] is a special [`Node`] that will automatically run the node for each view
            // matching the [`ViewQuery`]
            .add_render_graph_node::<ViewNodeRunner<PostProcessNode>>(
                // Specify the label of the graph, in this case we want the graph for 3d
                Core3d,
                // It also needs the label of the node
                PostProcessLabel,
            )
            .add_render_graph_edges(
                Core3d,
                // Specify the node ordering.
                // This will automatically create all required node edges to enforce the given ordering.
                (
                    Node3d::Tonemapping,
                    PostProcessLabel,
                    Node3d::EndMainPassPostProcessing,
                ),
            );
    }

    fn finish(&self, app: &mut App) {
        // We need to get the render app from the main app
        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
            return;
        };

        render_app
            // Initialize the pipeline
            .init_resource::<PostProcessPipeline>();
    }

pub fn insert_sub_app(&mut self, label: impl AppLabel, sub_app: SubApp)

Inserts a SubApp with the given label.

pub fn remove_sub_app(&mut self, label: impl AppLabel) -> Option<SubApp>

Removes the SubApp with the given label, if it exists.

pub fn add_schedule(&mut self, schedule: Schedule) -> &mut App

Inserts a new schedule under the provided label, overwriting any existing schedule with the same label.

Examples found in repository?
examples/ecs/custom_schedule.rs (line 25)
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
fn main() {
    let mut app = App::new();

    // Create a new [`Schedule`]. For demonstration purposes, we configure it to use a single threaded executor so that
    // systems in this schedule are never run in parallel. However, this is not a requirement for custom schedules in
    // general.
    let mut custom_update_schedule = Schedule::new(SingleThreadedUpdate);
    custom_update_schedule.set_executor_kind(ExecutorKind::SingleThreaded);

    // Adding the schedule to the app does not automatically run the schedule. This merely registers the schedule so
    // that systems can look it up using the `Schedules` resource.
    app.add_schedule(custom_update_schedule);

    // Bevy `App`s have a `main_schedule_label` field that configures which schedule is run by the App's `runner`.
    // By default, this is `Main`. The `Main` schedule is responsible for running Bevy's main schedules such as
    // `Update`, `Startup` or `Last`.
    //
    // We can configure the `Main` schedule to run our custom update schedule relative to the existing ones by modifying
    // the `MainScheduleOrder` resource.
    //
    // Note that we modify `MainScheduleOrder` directly in `main` and not in a startup system. The reason for this is
    // that the `MainScheduleOrder` cannot be modified from systems that are run as part of the `Main` schedule.
    let mut main_schedule_order = app.world_mut().resource_mut::<MainScheduleOrder>();
    main_schedule_order.insert_after(Update, SingleThreadedUpdate);

    // Adding a custom startup schedule works similarly, but needs to use `insert_startup_after`
    // instead of `insert_after`.
    app.add_schedule(Schedule::new(CustomStartup));

    let mut main_schedule_order = app.world_mut().resource_mut::<MainScheduleOrder>();
    main_schedule_order.insert_startup_after(PreStartup, CustomStartup);

    app.add_systems(SingleThreadedUpdate, single_threaded_update_system)
        .add_systems(CustomStartup, custom_startup_system)
        .add_systems(PreStartup, pre_startup_system)
        .add_systems(Startup, startup_system)
        .add_systems(First, first_system)
        .add_systems(Update, update_system)
        .add_systems(Last, last_system)
        .run();
}

pub fn init_schedule(&mut self, label: impl ScheduleLabel) -> &mut App

Initializes an empty schedule under the provided label, if it does not exist.

See add_schedule to insert an existing schedule.

Examples found in repository?
examples/games/stepping.rs (line 43)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
    fn build(&self, app: &mut App) {
        app.add_systems(Startup, build_stepping_hint);
        if cfg!(not(feature = "bevy_debug_stepping")) {
            return;
        }

        // create and insert our debug schedule into the main schedule order.
        // We need an independent schedule so we have access to all other
        // schedules through the `Stepping` resource
        app.init_schedule(DebugSchedule);
        let mut order = app.world_mut().resource_mut::<MainScheduleOrder>();
        order.insert_after(Update, DebugSchedule);

        // create our stepping resource
        let mut stepping = Stepping::new();
        for label in &self.schedule_labels {
            stepping.add_schedule(*label);
        }
        app.insert_resource(stepping);

        // add our startup & stepping systems
        app.insert_resource(State {
            ui_top: self.top,
            ui_left: self.left,
            systems: Vec::new(),
        })
        .add_systems(
            DebugSchedule,
            (
                build_ui.run_if(not(initialized)),
                handle_input,
                update_ui.run_if(initialized),
            )
                .chain(),
        );
    }

pub fn get_schedule(&self, label: impl ScheduleLabel) -> Option<&Schedule>

Returns a reference to the Schedule with the provided label if it exists.

pub fn get_schedule_mut( &mut self, label: impl ScheduleLabel ) -> Option<&mut Schedule>

Returns a mutable reference to the Schedule with the provided label if it exists.

pub fn edit_schedule( &mut self, label: impl ScheduleLabel, f: impl FnMut(&mut Schedule) ) -> &mut App

Runs function f with the Schedule associated with label.

Note: This will create the schedule if it does not already exist.

Examples found in repository?
examples/ecs/nondeterministic_system_order.rs (lines 25-30)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
fn main() {
    App::new()
        // We can modify the reporting strategy for system execution order ambiguities on a per-schedule basis.
        // You must do this for each schedule you want to inspect; child schedules executed within an inspected
        // schedule do not inherit this modification.
        .edit_schedule(Update, |schedule| {
            schedule.set_build_settings(ScheduleBuildSettings {
                ambiguity_detection: LogLevel::Warn,
                ..default()
            });
        })
        .init_resource::<A>()
        .init_resource::<B>()
        .add_systems(
            Update,
            (
                // This pair of systems has an ambiguous order,
                // as their data access conflicts, and there's no order between them.
                reads_a,
                writes_a,
                // This pair of systems has conflicting data access,
                // but it's resolved with an explicit ordering:
                // the .after relationship here means that we will always double after adding.
                adds_one_to_b,
                doubles_b.after(adds_one_to_b),
                // This system isn't ambiguous with adds_one_to_b,
                // due to the transitive ordering created by our constraints:
                // if A is before B is before C, then A must be before C as well.
                reads_b.after(doubles_b),
                // This system will conflict with all of our writing systems
                // but we've silenced its ambiguity with adds_one_to_b.
                // This should only be done in the case of clear false positives:
                // leave a comment in your code justifying the decision!
                reads_a_and_b.ambiguous_with(adds_one_to_b),
            ),
        )
        // Be mindful, internal ambiguities are reported too!
        // If there are any ambiguities due solely to DefaultPlugins,
        // or between DefaultPlugins and any of your third party plugins,
        // please file a bug with the repo responsible!
        // Only *you* can prevent nondeterministic bugs due to greedy parallelism.
        .add_plugins(DefaultPlugins)
        .run();
}

pub fn configure_schedules( &mut self, schedule_build_settings: ScheduleBuildSettings ) -> &mut App

Applies the provided ScheduleBuildSettings to all schedules.

pub fn allow_ambiguous_component<T>(&mut self) -> &mut App
where T: Component,

When doing ambiguity checking this ignores systems that are ambiguous on Component T.

This settings only applies to the main world. To apply this to other worlds call the corresponding method on World

§Example

#[derive(Component)]
struct A;

// these systems are ambiguous on A
fn system_1(_: Query<&mut A>) {}
fn system_2(_: Query<&A>) {}

let mut app = App::new();
app.configure_schedules(ScheduleBuildSettings {
  ambiguity_detection: LogLevel::Error,
  ..default()
});

app.add_systems(Update, ( system_1, system_2 ));
app.allow_ambiguous_component::<A>();

// running the app does not error.
app.update();

pub fn allow_ambiguous_resource<T>(&mut self) -> &mut App
where T: Resource,

When doing ambiguity checking this ignores systems that are ambiguous on Resource T.

This settings only applies to the main world. To apply this to other worlds call the corresponding method on World

§Example

#[derive(Resource)]
struct R;

// these systems are ambiguous on R
fn system_1(_: ResMut<R>) {}
fn system_2(_: Res<R>) {}

let mut app = App::new();
app.configure_schedules(ScheduleBuildSettings {
  ambiguity_detection: LogLevel::Error,
  ..default()
});
app.insert_resource(R);

app.add_systems(Update, ( system_1, system_2 ));
app.allow_ambiguous_resource::<R>();

// running the app does not error.
app.update();

pub fn ignore_ambiguity<M1, M2, S1, S2>( &mut self, schedule: impl ScheduleLabel, a: S1, b: S2 ) -> &mut App
where S1: IntoSystemSet<M1>, S2: IntoSystemSet<M2>,

Suppress warnings and errors that would result from systems in these sets having ambiguities (conflicting access but indeterminate order) with systems in set.

When possible, do this directly in the .add_systems(Update, a.ambiguous_with(b)) call. However, sometimes two independent plugins A and B are reported as ambiguous, which you can only suppress as the consumer of both.

Trait Implementations§

§

impl AddAudioSource for App

§

fn add_audio_source<T>(&mut self) -> &mut App
where T: Decodable + Asset, f32: FromSample<<T as Decodable>::DecoderItem>,

Registers an audio source. The type must implement Decodable, so that it can be converted to a rodio::Source type, and Asset, so that it can be registered as an asset. To use this method on App, the audio and asset plugins must be added first.
§

impl AddRenderCommand for App

§

fn add_render_command<P, C>(&mut self) -> &mut App
where P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static, <C as RenderCommand<P>>::Param: ReadOnlySystemParam,

Adds the RenderCommand for the specified render phase to the app.
§

impl AppGizmoBuilder for App

§

fn init_gizmo_group<T>(&mut self) -> &mut App

Registers GizmoConfigGroup T in the app enabling the use of Gizmos<T>. Read more
§

fn insert_gizmo_group<T>(&mut self, group: T, config: GizmoConfig) -> &mut App

Insert the GizmoConfigGroup in the app with the given value and GizmoConfig. Read more
§

impl AssetApp for App

§

fn register_asset_loader<L>(&mut self, loader: L) -> &mut App
where L: AssetLoader,

Registers the given loader in the App’s AssetServer.
§

fn register_asset_processor<P>(&mut self, processor: P) -> &mut App
where P: Process,

Registers the given processor in the App’s AssetProcessor.
§

fn register_asset_source( &mut self, id: impl Into<AssetSourceId<'static>>, source: AssetSourceBuilder ) -> &mut App

Registers the given AssetSourceBuilder with the given id. Read more
§

fn set_default_asset_processor<P>(&mut self, extension: &str) -> &mut App
where P: Process,

Sets the default asset processor for the given extension.
§

fn init_asset_loader<L>(&mut self) -> &mut App

Initializes the given loader in the App’s AssetServer.
§

fn init_asset<A>(&mut self) -> &mut App
where A: Asset,

Initializes the given Asset in the App by: Read more
§

fn register_asset_reflect<A>(&mut self) -> &mut App

Registers the asset type T using [App::register], and adds ReflectAsset type data to T and ReflectHandle type data to Handle<T> in the type registry. Read more
§

fn preregister_asset_loader<L>(&mut self, extensions: &[&str]) -> &mut App
where L: AssetLoader,

Preregisters a loader for the given extensions, that will block asset loads until a real loader is registered.
§

impl Debug for App

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Default for App

§

fn default() -> App

Returns the “default value” for a type. Read more
§

impl DynamicPluginExt for App

§

unsafe fn load_plugin<P>(&mut self, path: P) -> &mut App
where P: AsRef<OsStr>,

Dynamically links a plugin at the given path, registering the plugin. Read more
§

impl RegisterDiagnostic for App

§

fn register_diagnostic(&mut self, diagnostic: Diagnostic) -> &mut App

Register a new Diagnostic with an App. Read more
§

impl RenderGraphApp for App

§

fn add_render_graph_node<T>( &mut self, sub_graph: impl RenderSubGraph, node_label: impl RenderLabel ) -> &mut App
where T: Node + FromWorld,

Add a Node to the RenderGraph: Read more
§

fn add_render_graph_edge( &mut self, sub_graph: impl RenderSubGraph, output_node: impl RenderLabel, input_node: impl RenderLabel ) -> &mut App

Add node edge to the specified graph
§

fn add_render_graph_edges<const N: usize>( &mut self, sub_graph: impl RenderSubGraph, edges: impl IntoRenderNodeArray<N> ) -> &mut App

Automatically add the required node edges based on the given ordering
§

fn add_render_sub_graph(&mut self, sub_graph: impl RenderSubGraph) -> &mut App

Auto Trait Implementations§

§

impl !Freeze for App

§

impl !RefUnwindSafe for App

§

impl !Send for App

§

impl !Sync for App

§

impl Unpin for App

§

impl !UnwindSafe for App

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<S> FromSample<S> for S

§

fn from_sample_(s: S) -> S

§

impl<T> FromWorld for T
where T: Default,

§

fn from_world(_world: &mut World) -> T

Creates Self using data from the given World.
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

§

fn into_sample(self) -> T

§

impl<T> NoneValue for T
where T: Default,

§

type NoneType = T

§

fn null_value() -> T

The none-equivalent value.
§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
source§

impl<T> Same for T

§

type Output = T

Should always be Self
§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

§

fn to_sample_(self) -> U

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,