Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_ecs/examples/resources.rs
6598 views
1
//! In this example we add a counter resource and increase its value in one system,
2
//! while a different system prints the current count to the console.
3
4
#![expect(
5
clippy::std_instead_of_core,
6
clippy::print_stdout,
7
reason = "Examples should not follow this lint"
8
)]
9
10
use bevy_ecs::prelude::*;
11
use rand::Rng;
12
use std::ops::Deref;
13
14
fn main() {
15
// Create a world
16
let mut world = World::new();
17
18
// Add the counter resource
19
world.insert_resource(Counter { value: 0 });
20
21
// Create a schedule
22
let mut schedule = Schedule::default();
23
24
// Add systems to increase the counter and to print out the current value
25
schedule.add_systems((increase_counter, print_counter).chain());
26
27
for iteration in 1..=10 {
28
println!("Simulating frame {iteration}/10");
29
schedule.run(&mut world);
30
}
31
}
32
33
// Counter resource to be increased and read by systems
34
#[derive(Debug, Resource)]
35
struct Counter {
36
pub value: i32,
37
}
38
39
fn increase_counter(mut counter: ResMut<Counter>) {
40
if rand::rng().random_bool(0.5) {
41
counter.value += 1;
42
println!(" Increased counter value");
43
}
44
}
45
46
fn print_counter(counter: Res<Counter>) {
47
println!(" {:?}", counter.deref());
48
}
49
50