Let the object tell you when something happens.

The problem
Asking every frame.
int _lastHealth; void Update(){ if ( player.Health != _lastHealth ) { _lastHealth = player.Health; healthBar.Refresh( player.Health ); }}
The health bar asks 60 times a second. Health changes maybe once a minute.
The fix
Don't ask. Get told.
An event lets the player announce a change. Anyone interested signs up to hear it.
player→HealthChanged→health bar
The fix in code
Declare, invoke, subscribe.
// Playerpublic event Action<int> HealthChanged; public void TakeDamage( int amount ){ Health -= amount; HealthChanged?.Invoke( Health );} // HealthBarplayer.HealthChanged += Refresh;
The player fires the event when health changes. The bar's Refresh runs only then.
Watch out
Unsubscribe when you're done.
void OnDestroy(){ player.HealthChanged -= Refresh;}
Forget this and the player keeps calling a health bar that's already gone.
The rule
Something changed? Raise an event.
- Declare
- event Action<int> X
- Fire
- X?.Invoke( value )
- Clean up
- -= when destroyed