bevyengine/bevy
Resource
A resource is a globally-unique singleton stored on the World. There is at most one Time resource, one Assets<Image> resource, one WindowSettings resource — that's the kind of thing resources are for.
Defining
use bevy::prelude::*;
#[derive(Resource, Default)]
struct ScoreBoard {
score: u32,
}Insert and read:
app.insert_resource(ScoreBoard::default());
fn print_score(score: Res<ScoreBoard>) {
println!("{}", score.score);
}
fn award_points(mut score: ResMut<ScoreBoard>) {
score.score += 10;
}Res<T> is read-only; ResMut<T> is mutable. Two systems with ResMut<T> of the same T cannot run in parallel — the schedule executor enforces it.
Initialization
init_resource::<T>() (where T: FromWorld) initializes the resource via T::from_world(&mut World). Use this when initialization needs access to other resources or the asset server.
insert_resource(T) puts a known value in directly.
Removal
let removed = world.remove_resource::<MyResource>(); // returns Option<T>NonSend resources
Some types are not Send (think OS handles). They can still be resources via NonSendMut<T> and NonSend<T>. NonSend resources only run on the main thread; the schedule executor handles this transparently.
When to use a resource vs a component
| Pattern | Use |
|---|---|
| One value per world | Resource |
| One value per entity | Component |
| One value per system | Local<T> |
Don't put a HashMap<Entity, T> in a resource — that's just a bad component. Put T on the entity instead.
See also
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.