custom_loop/
custom_loop.rs

1//! This example demonstrates you can create a custom runner (to update an app manually). It reads
2//! lines from stdin and prints them from within the ecs.
3
4use bevy::{app::AppExit, prelude::*};
5use std::io;
6
7#[derive(Resource)]
8struct Input(String);
9
10fn my_runner(mut app: App) -> AppExit {
11    // Finalize plugin building, including running any necessary clean-up.
12    // This is normally completed by the default runner.
13    app.finish();
14    app.cleanup();
15
16    println!("Type stuff into the console");
17    for line in io::stdin().lines() {
18        {
19            let mut input = app.world_mut().resource_mut::<Input>();
20            input.0 = line.unwrap();
21        }
22        app.update();
23
24        if let Some(exit) = app.should_exit() {
25            return exit;
26        }
27    }
28
29    AppExit::Success
30}
31
32fn print_system(input: Res<Input>) {
33    println!("You typed: {}", input.0);
34}
35
36fn exit_system(input: Res<Input>, mut exit_event: EventWriter<AppExit>) {
37    if input.0 == "exit" {
38        exit_event.write(AppExit::Success);
39    }
40}
41
42// AppExit implements `Termination` so we can return it from main.
43fn main() -> AppExit {
44    App::new()
45        .insert_resource(Input(String::new()))
46        .set_runner(my_runner)
47        .add_systems(Update, (print_system, exit_system))
48        .run()
49}