2022-05-16 13:53:20 +00:00
|
|
|
//! Shows how anonymous functions / closures can be used as systems.
|
|
|
|
|
2022-04-27 18:02:07 +00:00
|
|
|
use bevy::{log::LogPlugin, prelude::*};
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
// create a simple closure.
|
|
|
|
let simple_closure = || {
|
|
|
|
// this is a closure that does nothing.
|
|
|
|
info!("Hello from a simple closure!");
|
|
|
|
};
|
|
|
|
|
|
|
|
// create a closure, with an 'input' value.
|
|
|
|
let complex_closure = |mut value: String| {
|
|
|
|
move || {
|
|
|
|
info!("Hello from a complex closure! {:?}", value);
|
|
|
|
|
|
|
|
// we can modify the value inside the closure. this will be saved between calls.
|
2022-10-28 21:03:01 +00:00
|
|
|
value = format!("{value} - updated");
|
2022-04-27 18:02:07 +00:00
|
|
|
|
|
|
|
// you could also use an outside variable like presented in the inlined closures
|
|
|
|
// info!("outside_variable! {:?}", outside_variable);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let outside_variable = "bar".to_string();
|
|
|
|
|
|
|
|
App::new()
|
2023-06-21 20:51:03 +00:00
|
|
|
.add_plugins(LogPlugin::default())
|
2022-04-27 18:02:07 +00:00
|
|
|
// we can use a closure as a system
|
2023-03-18 01:45:34 +00:00
|
|
|
.add_systems(Update, simple_closure)
|
2022-04-27 18:02:07 +00:00
|
|
|
// or we can use a more complex closure, and pass an argument to initialize a Local variable.
|
2023-03-18 01:45:34 +00:00
|
|
|
.add_systems(Update, complex_closure("foo".into()))
|
2022-04-27 18:02:07 +00:00
|
|
|
// we can also inline a closure
|
2023-03-18 01:45:34 +00:00
|
|
|
.add_systems(Update, || {
|
2022-04-27 18:02:07 +00:00
|
|
|
info!("Hello from an inlined closure!");
|
|
|
|
})
|
|
|
|
// or use variables outside a closure
|
2023-03-18 01:45:34 +00:00
|
|
|
.add_systems(Update, move || {
|
2022-04-27 18:02:07 +00:00
|
|
|
info!(
|
|
|
|
"Hello from an inlined closure that captured the 'outside_variable'! {:?}",
|
|
|
|
outside_variable
|
|
|
|
);
|
|
|
|
// you can use outside_variable, or any other variables inside this closure.
|
|
|
|
// their states will be saved.
|
|
|
|
})
|
|
|
|
.run();
|
|
|
|
}
|