summaryrefslogtreecommitdiff
path: root/ecs/examples
diff options
context:
space:
mode:
authorHampusM <hampus@hampusmat.com>2024-04-09 22:25:03 +0200
committerHampusM <hampus@hampusmat.com>2024-04-09 22:25:03 +0200
commit9d8c73dd2671131929967214433dae5479e95b5b (patch)
treed522d975e14e6db7544474b641d824edd8edbae5 /ecs/examples
parent50234ddc9ee7acd6d2b8d0a5626caf9e9293c0da (diff)
feat(ecs): add support for singleton components
Diffstat (limited to 'ecs/examples')
-rw-r--r--ecs/examples/with_single.rs71
1 files changed, 71 insertions, 0 deletions
diff --git a/ecs/examples/with_single.rs b/ecs/examples/with_single.rs
new file mode 100644
index 0000000..25b73d1
--- /dev/null
+++ b/ecs/examples/with_single.rs
@@ -0,0 +1,71 @@
+use ecs::component::single::Single;
+use ecs::event::{Event, Id as EventId};
+use ecs::{Component, Query, World};
+
+#[derive(Component)]
+struct Ammo
+{
+ ammo_left: u32,
+}
+
+#[derive(Component, Default)]
+struct AmmoCounter
+{
+ counter: u32,
+}
+
+fn count_ammo(query: Query<(Ammo,)>, mut ammo_counter: Single<AmmoCounter>)
+{
+ for (ammo,) in &query {
+ println!("Found {} ammo", ammo.ammo_left);
+
+ ammo_counter.counter += ammo.ammo_left;
+ }
+}
+
+fn print_total_ammo_count(ammo_counter: Single<AmmoCounter>)
+{
+ println!("Total ammo count: {}", ammo_counter.counter);
+
+ assert_eq!(ammo_counter.counter, 19);
+}
+
+#[derive(Debug)]
+struct EventA;
+
+impl Event for EventA
+{
+ fn id(&self) -> EventId
+ {
+ EventId::of::<Self>()
+ }
+}
+
+#[derive(Debug)]
+struct EventB;
+
+impl Event for EventB
+{
+ fn id(&self) -> EventId
+ {
+ EventId::of::<Self>()
+ }
+}
+
+fn main()
+{
+ let mut world = World::new();
+
+ world.register_system(&EventA, count_ammo);
+ world.register_system(&EventB, print_total_ammo_count);
+
+ world.create_entity((Ammo { ammo_left: 4 },));
+ world.create_entity((Ammo { ammo_left: 7 },));
+ world.create_entity((Ammo { ammo_left: 8 },));
+
+ world.add_single_component(AmmoCounter::default()).unwrap();
+
+ world.emit(&EventA);
+
+ world.emit(&EventB);
+}