Different Implementations of Death

Let’s say that I would make RTS with 1000 different units. Each unit has an attached Health component. Whenever their health reaches zero or less and they die, each unit should respond very differently.

Examples:

  • Unit #1 Should instantiate an appropriate prefab
  • Unit #2 Should grab the Health component of every nearby unit and deal damage
  • Unit #3 Should play a sound
  • Etc.

The main point is that every unit would have different logic / implementation of the way they die. My main hurdle is that I come from the hardcore OOP camp. So I would just make a base Unit class, have an (abstract) Death() method and extend it for every unit.

What would be the Unity way of doing this?

Components. Even in OOP, you can make a distinction between “is a” (inheritance) and “has a” (composition).

You could make each death a MonoBehaviour that responds to the message “OnDeath”. When the unit dies, you just need to SendMessage(“OnDeath”) and let the attached MonoBehaviour handle it. Since a unit isn’t dying every single frame of its existence, it’s not inefficient to use SendMessage().

Example:

public class InstantiateOnDeath : MonoBehaviour {

    public GameObject prefab;

    public void OnDeath() {
        Instantiate(prefab);
    }
}

public class PlaySoundOnDeath : MonoBehaviour {

    public void OnDeath() {
        audio.Play();
    }
}

And just add the appropriate script to each unit.