Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/ecs/system_closure.rs
6592 views
1
//! Shows how anonymous functions / closures can be used as systems.
2
3
use bevy::{log::LogPlugin, prelude::*};
4
5
fn main() {
6
// create a simple closure.
7
let simple_closure = || {
8
// this is a closure that does nothing.
9
info!("Hello from a simple closure!");
10
};
11
12
// create a closure, with an 'input' value.
13
let complex_closure = |mut value: String| {
14
move || {
15
info!("Hello from a complex closure! {}", value);
16
17
// we can modify the value inside the closure. this will be saved between calls.
18
value = format!("{value} - updated");
19
20
// you could also use an outside variable like presented in the inlined closures
21
// info!("outside_variable! {}", outside_variable);
22
}
23
};
24
25
let outside_variable = "bar".to_string();
26
27
App::new()
28
.add_plugins(LogPlugin::default())
29
// we can use a closure as a system
30
.add_systems(Update, simple_closure)
31
// or we can use a more complex closure, and pass an argument to initialize a Local variable.
32
.add_systems(Update, complex_closure("foo".into()))
33
// we can also inline a closure
34
.add_systems(Update, || {
35
info!("Hello from an inlined closure!");
36
})
37
// or use variables outside a closure
38
.add_systems(Update, move || {
39
info!(
40
"Hello from an inlined closure that captured the 'outside_variable'! {}",
41
outside_variable
42
);
43
// you can use outside_variable, or any other variables inside this closure.
44
// their states will be saved.
45
})
46
.run();
47
}
48
49