Added example of creating a system from a closure (#4327)

Fixes #4262
This commit is contained in:
Nathan Pinard 2022-04-27 18:02:07 +00:00
parent 71a246ce9e
commit f1aae380ab
3 changed files with 50 additions and 0 deletions

View file

@ -391,6 +391,10 @@ path = "examples/ecs/state.rs"
name = "system_chaining"
path = "examples/ecs/system_chaining.rs"
[[example]]
name = "system_closure"
path = "examples/ecs/system_closure.rs"
[[example]]
name = "system_param"
path = "examples/ecs/system_param.rs"

View file

@ -190,6 +190,7 @@ Example | File | Description
`startup_system` | [`ecs/startup_system.rs`](./ecs/startup_system.rs) | Demonstrates a startup system (one that runs once when the app starts up)
`state` | [`ecs/state.rs`](./ecs/state.rs) | Illustrates how to use States to control transitioning from a Menu state to an InGame state
`system_chaining` | [`ecs/system_chaining.rs`](./ecs/system_chaining.rs) | Chain two systems together, specifying a return type in a system (such as `Result`)
`system_closure` | [`ecs/system_closure.rs`](./ecs/system_closure.rs) | Show how to use closures as systems, and how to configure `Local` variables by capturing external state
`system_param` | [`ecs/system_param.rs`](./ecs/system_param.rs) | Illustrates creating custom system parameters with `SystemParam`
`system_sets` | [`ecs/system_sets.rs`](./ecs/system_sets.rs) | Shows `SystemSet` use along with run criterion
`timers` | [`ecs/timers.rs`](./ecs/timers.rs) | Illustrates ticking `Timer` resources inside systems and handling their state

View file

@ -0,0 +1,45 @@
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.
value = format!("{} - updated", value);
// 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()
.add_plugin(LogPlugin)
// we can use a closure as a system
.add_system(simple_closure)
// or we can use a more complex closure, and pass an argument to initialize a Local variable.
.add_system(complex_closure("foo".into()))
// we can also inline a closure
.add_system(|| {
info!("Hello from an inlined closure!");
})
// or use variables outside a closure
.add_system(move || {
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();
}