#Running a function when the app is shutting down.
11 messages · Page 1 of 1 (latest)
Very basic way to do that would be something like this:
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(PhysicsPlugins::default())
.add_plugins(PhysicsDebugPlugin::default())
.add_plugins(WorldInspectorPlugin::default())
.add_systems(Startup, startup)
.add_systems(
Update,
spawn_player_ball.run_if(input_just_pressed(KeyCode::Space)),
)
.run();
println!("This gets run once app is closed");
}
oh, thank you so much.
otherwise there is this Event you can listen to too: https://docs.rs/bevy/latest/bevy/window/struct.WindowClosed.html
An event that is sent whenever a window is closed. This will be sent when the window entity loses its Window component or is despawned.
Window has a bunch of other events too, like ClosingWindow (window is about to be closed): https://docs.rs/bevy/latest/bevy/window/index.html
bevy_window provides a platform-agnostic interface for windowing in Bevy.
that is really useful. ty
do I listen for the event in a update function?
Yup, you might want to use WindowClosing though I think on second thought, as WindowClosed might be too late, don't remember exactly
I tried both and it only got called with WindowClosing so I'll use that
You should use AppExit if you want to run something when it's shutting down - a window closing is not guaranteed to do that, though it will if it's the only window and you're using the default behavior.
.add_systems(PostUpdate, do_stuff_on_exit.run_if(on_event::<AppExit>()).after(exit_on_primary_closed).after(exit_on_all_closed))```
I believe that snippet was originally for someone who needed to run something in PostUpdate specifically, this might work better for you rs .add_systems(Last, do_stuff_on_exit.run_if(on_event::<AppExit>()))