From 6fb353932990ad7d16a2455ac49b858e2069f65c Mon Sep 17 00:00:00 2001 From: Robert Garrett Date: Sat, 30 Aug 2025 09:21:57 -0500 Subject: [PATCH] Use hook on FuelGauge to show text on first spawn There is an on-add hook that can be used to maintain invariants. I'll use it to ensure the label text always gets the current fuel value upon spawning the widget, regardless of whether or not the caller remembers to set it up themselves. --- src/widgets/fuel_gauge.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/widgets/fuel_gauge.rs b/src/widgets/fuel_gauge.rs index 234a066..ef73c8b 100644 --- a/src/widgets/fuel_gauge.rs +++ b/src/widgets/fuel_gauge.rs @@ -1,9 +1,15 @@ -use bevy::{color::palettes::css::*, prelude::*, ui::Val::*}; +use bevy::{ + color::palettes::css::*, + ecs::{component::HookContext, world::DeferredWorld}, + prelude::*, + ui::Val::*, +}; use crate::game::consumables::{Fuel, FuelChanged}; #[derive(Component)] #[require(Label)] +#[component(on_add = FuelGauge::refresh_label)] pub struct FuelGauge(Entity); impl FuelGauge { @@ -41,4 +47,23 @@ impl FuelGauge { ); label.0 = format!("Fuel: {}", fuel.0); } + + fn refresh_label(mut world: DeferredWorld, ctx: HookContext) { + // Get the machine ID from the FuelGauge component. + let Some(machine_id) = world.get::(ctx.entity).map(|fg| fg.0) else { + panic!("Couldn't get a FuelGauge during it's on-add hook run!"); + }; + // and fuel level + let Some(fuel) = world.get::(machine_id).map(|lvl| lvl.0) else { + // TODO: Maybe don't panic and just emit a warning. + panic!("Couldn't get a Fuel for a machine during a FuelGauge on-add hook."); + }; + + // Get an excl ref to the Text component so we can redraw its text + let Some(mut label) = world.get_mut::(ctx.entity) else { + panic!() + }; + + label.0 = format!("Fuel: {}", fuel); + } }