An enclave for thoughts

Using a bevy Resource to signal completion states in a game

Resources

In the Bevy engine ecosystem, globally accessible data structures can be declared as resources that may be inserted into the application.
To create a resource declaration, use #[derive(Resource)] on a struct, Example:

#[derive(Resource)]
struct MyResource {
	completed_phase_1: bool,
	completed_phase_2: bool,
	inventory: Vec<Thing>,
	// etc...
}

We can now reference MyResource, and insert it into the application. To do this, use the insert_resource method. Example:


fn main() {
	let app = App::new()
		// ...
		.insert_resource(
			MyResource {
				completed_phase_1: false, 
				completed_phase_2: false, 
				inventory: Vec::new()
			}
		)
		.run();
}

But I want to insert a resource conditionally

You can insert a resource after the application is initialised by using Commands of the application in a system.

fn insert_resource_if_condition(
	mut commands: Commands,
) {
	commands.insert_resource(/*the resource*/);
	// ...
}

NOTE: beware of misplaced resource insertions that may cause too many resources to be spawned.

, , , , — Mar 30, 2025