Struct bevy::app::App

source ·
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§

source§

impl App

source

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/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();
}
examples/2d/sprite.rs (line 6)
5
6
7
8
9
10
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
source

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.

source

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 22)
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn my_runner(mut app: App) -> AppExit {
    // Finalize plugin building, including running any necessary clean-up.
    // This is normally completed by the default runner.
    app.finish();
    app.cleanup();

    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();

        if let Some(exit) = app.should_exit() {
            return exit;
        }
    }

    AppExit::Success
}
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 45)
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
fn runner(mut app: App) -> AppExit {
    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();
            }
        }
    }

    AppExit::Success
}
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();
}
source

pub fn run(&mut self) -> AppExit

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/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();
}
examples/2d/sprite.rs (line 9)
5
6
7
8
9
10
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
source

pub fn set_runner( &mut self, f: impl FnOnce(App) -> AppExit + '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) -> AppExit {
    loop {
        println!("In main loop");
        app.update();
        if let Some(exit) = app.should_exit() {
            return exit;
        }
    }
}

App::new()
    .set_runner(my_runner);
Examples found in repository?
examples/app/custom_loop.rs (line 46)
43
44
45
46
47
48
49
fn main() -> AppExit {
    App::new()
        .insert_resource(Input(String::new()))
        .set_runner(my_runner)
        .add_systems(Update, (print_system, exit_system))
        .run()
}
More examples
Hide additional examples
examples/time/time.rs (line 118)
110
111
112
113
114
115
116
117
118
119
120
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();
}
source

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.

source

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.

Examples found in repository?
examples/app/custom_loop.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 my_runner(mut app: App) -> AppExit {
    // Finalize plugin building, including running any necessary clean-up.
    // This is normally completed by the default runner.
    app.finish();
    app.cleanup();

    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();

        if let Some(exit) = app.should_exit() {
            return exit;
        }
    }

    AppExit::Success
}
source

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.

Examples found in repository?
examples/app/custom_loop.rs (line 14)
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn my_runner(mut app: App) -> AppExit {
    // Finalize plugin building, including running any necessary clean-up.
    // This is normally completed by the default runner.
    app.finish();
    app.cleanup();

    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();

        if let Some(exit) = app.should_exit() {
            return exit;
        }
    }

    AppExit::Success
}
source

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

Adds one or more systems to the given schedule in this app’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/2d/mesh2d.rs (line 8)
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 12)
9
10
11
12
13
14
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
examples/2d/sprite.rs (line 8)
5
6
7
8
9
10
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
source

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.

source

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();
}
source

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 custom_layer(app: &mut App) -> Option<BoxedLayer> {
    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);

    Some(layer.boxed())
}
source

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/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();
}
More examples
Hide additional examples
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/app/custom_loop.rs (line 45)
43
44
45
46
47
48
49
fn main() -> AppExit {
    App::new()
        .insert_resource(Input(String::new()))
        .set_runner(my_runner)
        .add_systems(Update, (print_system, exit_system))
        .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();
}
source

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/3d/clearcoat.rs (line 52)
50
51
52
53
54
55
56
57
58
59
pub fn main() {
    App::new()
        .init_resource::<LightMode>()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, animate_light)
        .add_systems(Update, animate_spheres)
        .add_systems(Update, (handle_input, update_help_text).chain())
        .run();
}
source

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 custom_layer(app: &mut App) -> Option<BoxedLayer> {
    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);

    Some(layer.boxed())
}
source

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

Inserts the !Send resource 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.

source

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

Returns true if the Plugin has already been added.

source

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;
source

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/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();
}
examples/2d/transparency_2d.rs (line 8)
6
7
8
9
10
11
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .run();
}
source

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();
}
source

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.

source

pub fn world(&self) -> &World

Returns a reference to the World.

source

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 19)
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn my_runner(mut app: App) -> AppExit {
    // Finalize plugin building, including running any necessary clean-up.
    // This is normally completed by the default runner.
    app.finish();
    app.cleanup();

    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();

        if let Some(exit) = app.should_exit() {
            return exit;
        }
    }

    AppExit::Success
}
More examples
Hide additional examples
examples/2d/mesh2d_manual.rs (line 283)
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
    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>>()
            .init_resource::<RenderColoredMesh2dInstances>()
            .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 49)
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
fn runner(mut app: App) -> AppExit {
    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();
            }
        }
    }

    AppExit::Success
}
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();
}
source

pub fn main(&self) -> &SubApp

Returns a reference to the main SubApp.

source

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

Returns a mutable reference to the main SubApp.

source

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.

source

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 335)
327
328
329
330
331
332
333
334
335
336
337
        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 107)
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
    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/app/headless_renderer.rs (line 206)
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
    fn build(&self, app: &mut App) {
        let (s, r) = crossbeam_channel::unbounded();

        let render_app = app
            .insert_resource(MainWorldReceiver(r))
            .sub_app_mut(RenderApp);

        let mut graph = render_app.world_mut().resource_mut::<RenderGraph>();
        graph.add_node(ImageCopy, ImageCopyDriver);
        graph.add_node_edge(bevy::render::graph::CameraDriverLabel, ImageCopy);

        render_app
            .insert_resource(RenderWorldSender(s))
            // Make ImageCopiers accessible in RenderWorld system and plugin
            .add_systems(ExtractSchedule, image_copy_extract)
            // Receives image data from buffer to channel
            // so we need to run it after the render graph is done
            .add_systems(Render, receive_image_from_buffer.after(RenderSet::Render));
    }
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());
    }
source

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

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

source

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 42)
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
    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 290)
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
    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>>()
            .init_resource::<RenderColoredMesh2dInstances>()
            .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/custom_phase_item.rs (line 185)
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
fn main() {
    let mut app = App::new();
    app.add_plugins(DefaultPlugins)
        .add_plugins(ExtractComponentPlugin::<CustomRenderedEntity>::default())
        .add_systems(Startup, setup)
        // Make sure to tell Bevy to check our entity for visibility. Bevy won't
        // do this by default, for efficiency reasons.
        .add_systems(
            PostUpdate,
            view::check_visibility::<WithCustomRenderedEntity>
                .in_set(VisibilitySystems::CheckVisibility),
        );

    // We make sure to add these to the render app, not the main app.
    app.get_sub_app_mut(RenderApp)
        .unwrap()
        .init_resource::<CustomPhasePipeline>()
        .init_resource::<SpecializedRenderPipelines<CustomPhasePipeline>>()
        .add_render_command::<Opaque3d, DrawCustomPhaseItemCommands>()
        .add_systems(
            Render,
            prepare_custom_phase_item_buffers.in_set(RenderSet::Prepare),
        )
        .add_systems(Render, queue_custom_phase_item.in_set(RenderSet::Queue));

    app.run();
}
examples/shader/post_processing.rs (line 63)
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
    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>();
    }
source

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

Inserts a SubApp with the given label.

source

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

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

source

pub fn update_sub_app_by_label(&mut self, label: impl AppLabel)

Extract data from the main world into the SubApp with the given label and perform an update if it exists.

source

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();
}
source

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(),
        );
    }
source

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

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

source

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.

source

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();
}
source

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

Applies the provided ScheduleBuildSettings to all schedules.

source

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();
source

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();
source

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.

source

pub fn should_exit(&self) -> Option<AppExit>

Attempts to determine if an AppExit was raised since the last update.

Will attempt to return the first Error it encounters. This should be called after every update() otherwise you risk dropping possible AppExit events.

Examples found in repository?
examples/app/custom_loop.rs (line 24)
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn my_runner(mut app: App) -> AppExit {
    // Finalize plugin building, including running any necessary clean-up.
    // This is normally completed by the default runner.
    app.finish();
    app.cleanup();

    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();

        if let Some(exit) = app.should_exit() {
            return exit;
        }
    }

    AppExit::Success
}
source

pub fn observe<E, B, M>( &mut self, observer: impl IntoObserverSystem<E, B, M>, ) -> &mut App
where E: Event, B: Bundle,

Spawns an Observer entity, which will watch for and respond to the given event.

Examples found in repository?
examples/ecs/observers.rs (lines 18-36)
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
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .init_resource::<SpatialIndex>()
        .add_systems(Startup, setup)
        .add_systems(Update, (draw_shapes, handle_click))
        // Observers are systems that run when an event is "triggered". This observer runs whenever
        // `ExplodeMines` is triggered.
        .observe(
            |trigger: Trigger<ExplodeMines>,
             mines: Query<&Mine>,
             index: Res<SpatialIndex>,
             mut commands: Commands| {
                // You can access the trigger data via the `Observer`
                let event = trigger.event();
                // Access resources
                for e in index.get_nearby(event.pos) {
                    // Run queries
                    let mine = mines.get(e).unwrap();
                    if mine.pos.distance(event.pos) < mine.size + event.radius {
                        // And queue commands, including triggering additional events
                        // Here we trigger the `Explode` event for entity `e`
                        commands.trigger_targets(Explode, e);
                    }
                }
            },
        )
        // This observer runs whenever the `Mine` component is added to an entity, and places it in a simple spatial index.
        .observe(on_add_mine)
        // This observer runs whenever the `Mine` component is removed from an entity (including despawning it)
        // and removes it from the spatial index.
        .observe(on_remove_mine)
        .run();
}

Trait Implementations§

source§

impl AddAudioSource for App

source§

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

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.
source§

impl AddRenderCommand for App

source§

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.
source§

impl AppExtStates for App

source§

fn init_state<S>(&mut self) -> &mut App

Initializes a State with standard starting values. Read more
source§

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

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

fn add_computed_state<S>(&mut self) -> &mut App
where S: ComputedStates,

Sets up a type implementing ComputedStates. Read more
source§

fn add_sub_state<S>(&mut self) -> &mut App
where S: SubStates,

Sets up a type implementing SubStates. Read more
source§

fn enable_state_scoped_entities<S>(&mut self) -> &mut App
where S: States,

Enable state-scoped entity clearing for state S. Read more
source§

impl AppGizmoBuilder for App

source§

fn init_gizmo_group<Config>(&mut self) -> &mut App
where Config: GizmoConfigGroup,

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

fn insert_gizmo_config<Config>( &mut self, group: Config, config: GizmoConfig, ) -> &mut App
where Config: GizmoConfigGroup,

Insert a GizmoConfig into a specific GizmoConfigGroup. Read more
source§

impl AssetApp for App

source§

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

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

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

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

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
source§

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

Sets the default asset processor for the given extension.
source§

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

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

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

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

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
source§

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.
source§

impl Debug for App

source§

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

Formats the value using the given formatter. Read more
source§

impl Default for App

source§

fn default() -> App

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

impl DynamicPluginExt for App

source§

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

👎Deprecated since 0.14.0: The current dynamic plugin system is unsound and will be removed in 0.15.
Dynamically links a plugin at the given path, registering the plugin. Read more
source§

impl RegisterDiagnostic for App

source§

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

Register a new Diagnostic with an App. Read more
source§

impl RenderGraphApp for App

source§

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
source§

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
source§

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
source§

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
source§

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

source§

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
source§

impl<T> Downcast<T> for T

source§

fn downcast(&self) -> &T

source§

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

source§

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.
source§

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.
source§

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.
source§

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.

source§

impl<S> FromSample<S> for S

source§

fn from_sample_(s: S) -> S

source§

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

source§

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

Creates Self using data from the given World.
source§

impl<T> Instrument for T

source§

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

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

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.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

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

source§

fn into_sample(self) -> T

source§

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

§

type NoneType = T

source§

fn null_value() -> T

The none-equivalent value.
source§

impl<T> Pointable for T

source§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
source§

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

Initializes a with the given initializer. Read more
source§

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

Dereferences the given pointer. Read more
source§

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

Mutably dereferences the given pointer. Read more
source§

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
source§

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

source§

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.
source§

impl<T> Upcast<T> for T

source§

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

source§

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

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

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
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

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