Menu
CoddyTech

Health and Damage

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 55 of 71.

Damage takes two scripts. A Health script sits on everything that can be hurt and owns its hit points, and whatever does the hurting finds that script and calls a method on it. Here is the Health of a crate that breaks after three hits, and spikes that hurt whatever lands on them:

public class Health : MonoBehaviour
{
    [SerializeField] private int hp = 3;

    public void TakeDamage(int amount)
    {
        hp -= amount;
        if (hp <= 0)
        {
            Destroy(gameObject);
        }
    }
}
public class Spikes : MonoBehaviour
{
    void OnCollisionEnter(Collision collision)
    {
        Health health = collision.gameObject.GetComponent<Health>();
        if (health != null)
        {
            health.TakeDamage(1);
        }
    }
}

TakeDamage is public, so other scripts can call it, and it is the only code that changes hp. Spikes, bullets and lava all call the same method, and the Health script alone decides what 0 means: destroy the crate, end the game or play a death animation. Each script lives in its own file, named after its class.

GetComponent<Health>() returns null for things that have no Health, such as the floor, so the spikes check before calling. TryGetComponent(out Health health) does the lookup and the check in one call: it returns true and fills in health only when there is one.

challenge icon

Challenge

Medium

Make the hits count. Bullet is ready and calls TakeDamage(2) on what it hits.

  1. In Health, fill in TakeDamage(int amount): take Mathf.Max(amount - armor, 1) off hp.
  2. Log name + " hp: " + hp, for example Dummy hp: 2.
  3. When hp <= 0, call Destroy(gameObject);.

Press Play and shoot the dummy twice: it logs Dummy hp: 2, then vanishes. Then Check.

Try it yourself

using UnityEngine;

public class Health : MonoBehaviour
{
    [SerializeField] private int hp = 4;
    [SerializeField] private int armor = 0;

    public void TakeDamage(int amount)
    {
        // lose amount minus armor (at least 1), log what is left, destroy at 0
    }
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground