Skip to content

Latest commit

 

History

History
57 lines (43 loc) · 2 KB

they_are_singleton_structs.md

File metadata and controls

57 lines (43 loc) · 2 KB

They Are Singleton Structs

Most of the time, we would like to access data of our structs when we are using systems. If we only need one instance of such structs, we can use the Resource trait and add the Resource to our App.

To do so, we need to have a struct that derives the Resource macro. We can use the insert_resource method of App to add an instance of the struct. Then we can access the struct in our systems by declaring a parameter Res<MyResource> where MyResource is the name of the struct.

use bevy::{
    app::{App, Startup},
    ecs::system::{Res, Resource},
};

fn main() {
    App::new()
        .insert_resource(MyResource { value: 10 })
        .add_systems(Startup, output_value)
        .run();
}

#[derive(Resource)]
struct MyResource {
    value: u32,
}

fn output_value(r: Res<MyResource>) {
    println!("{}", r.value);
}

Output:

10

If MyResource has implemented the Default trait:

impl Default for MyResource {
    fn default() -> Self {
        Self { value: 10 }
    }
}

Then we can use the init_resource method of App to initialize the struct instead of calling insert_resource.

init_resource::<MyResource>()

➡️ Next: Updating Resources

📘 Back: Table of contents