Tainted\\Coders

Bevy Resources

Bevy version: 0.16Last updated:

Resources are used to hold shared data not specific to any single entity. They are global singleton data structures that can be conveniently passed around between your systems.

Some examples of common resources are:

Each World can only have a single resource of each type at a time. A good gut check for whether you want a resource or component is if you need more than one.

Defining a resource

We create resources just like components by deriving the Resource trait:

#[derive(Resource)]
struct Score(usize);

This will only define the resource. To have this resource be created at the start of our App we have to add it.

Adding a resource

The most simple way of adding a resource is to insert_resource with a valid instance:

fn main() {
  App::new()
    .add_plugins(DefaultPlugins)
    .insert_resource(Score(0))
    .run();
}

If we implement either Default or FromWorld traits on our resources then we can skip creating the instance ourself and allow Bevy to do that for us with init_resource<T>:

#[derive(Resource, Default)]
struct Score(usize);

fn main() {
  App::new()
    .add_plugins(DefaultPlugins)
    .init_resource::<Score>()
    .run();
}

Resources can also be added more dynamically through your systems

fn add_score(mut commands: Commands) {
  commands.insert_resource(Score(0));
}

Removing a resource

To remove a resource at runtime you can use your Commands inside any system.

fn remove_score(mut commands: Commands) {
  commands.remove_resource::<Score>();
}

Reading and writing resources

To read and write a resource's data we use the Res and ResMut system parameters:

fn increase_score(mut score: ResMut<Score>) {
  score.0 += 1;
  println!("Score: {}", score.0);
}

We should prefer to have resources initialized during the App definition. This will ensure they are available in our systems. If we were instead dynamically creating them you can use an Option to avoid a panic if they don't yet exist.

fn increase_score_if_present(mut score: Option<ResMut<Score>>) {
  if let Some(mut score) = score.as_deref_mut() {
    score.0 += 1;
    println!("Score: {}", score.0);
  } else {
    println!("No score resource found.");
  }
}