Damageable

Damageable

The damageable interface is used by objects or characters to take damage, heal and die. You can listen to those events to add functionality.

/// <summary>
/// The damageable interface.
/// </summary>
public interface IDamageable
{
    event Action OnHpChanged;
    event Action<Damage> OnTakeDamage;
    event Action<int> OnHeal;
    event Action OnDie;

    GameObject gameObject { get; }

    int MaxHp { get; }
    int CurrentHp { get; }

    void TakeDamage(int amount);
    void TakeDamage(Damage damage);
    
    void Heal(int amount);
    void Die();
}

/// <summary>
/// The damager interface.
/// </summary>
public interface IDamager
{
    GameObject gameObject { get; }
    int DamageTypeIndex { get; }
}

For example whenever a character’s health changes when taking damage or healing I update the health slider with the HealthMonitor.

When you want to damage a damageable it is as simple as to write:

damageable.TakeDamage(10);
//or
damageable.TakeDamage(damage);

You can instantly kill a damageable with:

damageable.Die();

When dying a character will re-spawn at a spawn point specified in the inspector.

The damage struct has information about the amount of damage, the direction, the damager and the damageable

/// <summary>
/// The damage object contains information about the damager, damageable, etc...
/// </summary>
[Serializable]
public struct Damage
{
    [Tooltip("The damage amount.")]
    [SerializeField] private int m_Amount;
    [Tooltip("The force in the the damager hit the damageable.")]
    [SerializeField] private Vector3 m_Force;
    [Tooltip("The damageable being hit.")]
    [SerializeField] private IDamageable m_Damageable;
    [Tooltip("The damager hitting the damageable.")]
    [SerializeField] private IDamager m_Damager;

    ...
}

As shown at the beginning of this section the damager has a damage type index which allows us to decide if a damage should be processed or not. For example in the demo we prevent the snowballs from being able to break the chains of the nice penguin by setting an index of 1 to the pickaxe damage type and a 0 for the snowball.