Bevy Version: | 0.9 | (outdated!) |
---|
Resources
Relevant official examples:
ecs_guide
.
Resources allow you to store a single global instance of some data type, independently of entities.
Use them for data that is truly global for your app, such as configuration / settings.
To create a new resource type, simply define a Rust struct
or enum
, and
derive the Resource
trait, similar to
components.
Types must be unique; there can only be one instance of a given type.
#[derive(Resource)]
struct GoalsReached {
main_goal: bool,
bonus: bool,
}
Resources can be accessed from systems, using Res
/ResMut
.
Resource Initialization
Implement Default
for simple resources:
#[derive(Resource, Default, Debug)]
struct StartingLevel(usize);
For resources that need complex initialization, implement FromWorld
:
#[derive(Resource)]
struct MyFancyResource { /* stuff */ }
impl FromWorld for MyFancyResource {
fn from_world(world: &mut World) -> Self {
// You have full access to anything in the ECS from here.
// For instance, you can mutate other resources:
let mut x = world.get_resource_mut::<MyOtherResource>().unwrap();
x.do_mut_stuff();
MyFancyResource { /* stuff */ }
}
}
You can initialize your resources at App
creation:
fn main() {
App::new()
// ...
// if it implements `Default` or `FromWorld`
.init_resource::<MyFancyResource>()
// if not, or if you want to set a specific value
.insert_resource(StartingLevel(3))
// ...
.run();
}
Commands
can be used to create/remove resources from
inside a system:
commands.insert_resource(GoalsReached { main_goal: false, bonus: false });
commands.remove_resource::<MyResource>();
If you insert a resource of a type that already exists, it will be overwritten.
Usage Advice
The choice of when to use entities/components vs. resources is typically about how you want to access the data: globally from anywhere (resources), or using ECS patterns (entities/components).
Even if there is only one of a certain thing in your game (such as the player in a single-player game), it can be a good fit to use an entity instead of resources, because entities are composed of multiple components, some of which can be common with other entities. This can make your game logic more flexible. For example, you could have a "health/damage system" that works with both the player and enemies.