Menu
CoddyTech

Health and Damage

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 53 of 63.

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

A training gun fires at a dummy and an armored knight. The Shooter script on the Gun is ready: the left and right arrows turn it, and Space fires a Bullet. Write the two scripts that make the hits count.

Health, on the Dummy and the Knight (the Inspector sets hp and armor):

  • A public method TakeDamage(int amount): hp drops by amount minus armor, but always by at least 1.
  • After each hit, log the object's name and the hp left, as Dummy hp: 2.
  • At 0 hp or below, destroy the object.

Bullet, on each bullet (the Inspector sets damage to 2):

  • When the bullet hits something that has a Health, call its TakeDamage(damage).
  • Whatever it hits, the wall included, destroy the bullet.

Press Play, knock down the dummy and the knight, 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
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay