despawn_on_completion/
despawn_on_completion.rs

1use bevy::prelude::*;
2use bevy_local_commands::{BevyLocalCommandsPlugin, Cleanup, LocalCommand, ProcessCompleted};
3
4fn main() {
5    App::new()
6        .add_plugins((MinimalPlugins, BevyLocalCommandsPlugin))
7        .add_systems(Startup, startup)
8        .add_systems(Update, update)
9        .run();
10}
11
12fn startup(mut commands: Commands) {
13    // Choose the command based on the OS
14    #[cfg(not(windows))]
15    let cmd = LocalCommand::new("sh").args(["-c", "echo Sleeping for 1s && sleep 1 && echo Done"]);
16    #[cfg(windows)]
17    let cmd = LocalCommand::new("powershell").args(["echo 'Sleeping for 1s'; sleep 1; echo Done"]);
18
19    let id = commands.spawn((cmd, Cleanup::DespawnEntity)).id();
20    println!("Spawned the command as entity {id:?}");
21}
22
23fn update(
24    mut process_completed_event: MessageReader<ProcessCompleted>,
25    query: Query<Entity>,
26    mut entity: Local<Option<Entity>>,
27) {
28    if let Some(process_completed) = process_completed_event.read().last() {
29        *entity = Some(process_completed.entity);
30        println!(
31            "Command {:?} completed (Success - {})",
32            process_completed.entity,
33            process_completed.exit_status.success()
34        );
35    }
36    if entity.is_some() && query.get(entity.unwrap()).is_err() {
37        // Entity no longer exists, quit the app.
38        println!("Entity no longer exists, exiting");
39        std::process::exit(0);
40    }
41}