Local Resources

Relevant official examples: ecs_guide.


Local<T> is a system parameter similar to ResMut<T>, which gives you full mutable access to an instance of some data type, that is independent from entities and components.

Res<T>/ResMut<T> refer to a single global instance of the type, shared between all systems. On the other hand, every Local<T> parameter is a separate instance, exclusively for that system.

#[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
}

The type must implement Default or FromWorld. It is automatically initialized.

A system can have multiple Locals of the same type.

Specify an initial value

You can initialize a Local to a value other than the type's default, using .config, when adding your system to your App.

.config is Bevy's API for "configuring" specific system parameters. Most other types of system parameters do not support configuration, but Locals let you specify the initial value.

/// 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::build()
        .add_system(my_system.system().config(|params| {
            // our config is the third parameter in the system fn,
            // hence `.2`
            params.2 = Some(MyConfig {
                magic: 420,
            });
        }))
        .run();
}