Component that tracks hit points for anything damageable. Stores MaxHealth and Current, and fires Damaged on each hit and Killed once when Current reaches zero.
using System;
/// <summary>Hit points for anything that can be hurt and killed.</summary>
[Title( "Health" ), Category( "Combat" ), Icon( "favorite" )]
public sealed class Health : Component
{
[Property] public float MaxHealth { get; set; } = 100f;
public float Current { get; private set; }
public bool IsDead { get; private set; }
/// <summary>Raised on every hit that lands: amount, attacker (may be null).</summary>
public event Action<float, GameObject> Damaged;
/// <summary>Raised once when health reaches zero: the attacker (may be null).</summary>
public event Action<GameObject> Killed;
protected override void OnStart() => Current = MaxHealth;
public void Damage( float amount, GameObject attacker = null )
{
if ( IsDead || amount <= 0f ) return;
Current = MathF.Max( Current - amount, 0f );
Damaged?.Invoke( amount, attacker );
if ( Current > 0f ) return;
IsDead = true;
Killed?.Invoke( attacker );
}
}