本地资源
可参考的官方例子:
ecs_guide
.
本地资源允许你拥有属于每个系统自己的数据。
Local<T>
是一个类似于 ResMut<T>
的系统参数,它让你可以完全地读写访问某个数据类型的实例,这实例是独立于实体和组件。
Res<T>
/ResMut<T>
引用的是某数据类型的一个全局实例,可以在所有系统之间共享。与之对应,每个 Local<T>
参数引用的都是一个单独的实例,专属于该系统。
#[derive(Default)]
struct MyState;
fn my_system1(mut local: Local<MyState>) {
// you can do anything you want with the local here
}
fn my_system2(mut local: Local<MyState>) {
// the local in this system is a different instance
}
作为本地资源的类型必须实现 Default
或 FromWorld
方法,它会被自动初始化。
一个系统可以有多个相同类型的 Local
参数。
指定一个初始值
你可以在把你的系统添加到你的 App
中时,使用系统的 .config
方法可以把 Local
初始化为该类型默认值以外的值。
.config
是 Bevy 的 API,用于"配置"特定的系统参数。系统的大多数其他类型的参数不支持配置,但 Local
允许你指定初始值。
/// Configuration for `my_system`.
///
/// The system will access it using `Local<MyConfig>`.
/// It will be initialized with the correct value at App build time.
///
/// Must still impl `Default`, because of requirement for `Local`.
#[derive(Default)]
struct MyConfig {
magic: usize,
}
fn my_system(
mut cmd: Commands,
my_res: Res<MyStuff>,
config: Local<MyConfig>,
) {
// TODO: do stuff
}
fn main() {
App::new()
.add_system(my_system.config(|params| {
// our config is the third parameter in the system fn,
// hence `.2`
params.2 = Some(MyConfig {
magic: 420,
});
}))
.run();
}