Why is your dead player still walking?

Two fields that should agree, and don't.

Why is your dead player still walking?

The problem

A flag you have to keep in sync.

int _health = 100;bool _isDead; public void TakeDamage( int amount ){    _health -= amount;    if ( _health <= 0 ) _isDead = true;} public void Poison() => _health -= 5;

Poison lowers health but never sets the flag. Every new way to lose health is a new chance to forget.

The fix

Work it out when you're asked.

If a value can be calculated from other values, calculate it. Then it can never be out of date.

IsDead=>_health <= 0

The fix in code

A property with an arrow.

int _health = 100; public bool IsDead => _health <= 0; public void TakeDamage( int amount ) => _health -= amount;public void Poison() => _health -= 5;

No flag to set. However health drops, IsDead is right the next time anyone reads it.

Watch out

It runs every time you read it.

Keep computed properties cheap. Whatever is in there runs on every single read.

A comparison
free, keep it
A search of the scene
store it instead
Read in a loop
the cost multiplies

The rule

If you can calculate it, don't store it.

Derived value
=> expression
No flag
nothing to forget
Expensive work
cache it instead