As another tool in your toolbox, in addition to the polymorphism Alex Myers recommends in the comments, you can try setting this up in an event-driven manner:
public class DamageTaker : MonoBehaviour {
public UnityEvent onDamage;
public float health;
public void TakeDamage(float damage) {
onDamage.Invoke();
health -= damage;
if(health <= 0f) {
// TODO: Handle death.
}
}
}
This will give you a widget in the Inspector (or an access point in code) where you can wire up no, one, or multiple methods to call when this object takes damage. These methods can be on the same script or different scripts, or even on different objects in your scene. You can even configure the event to pass the amount/type of damage taken, or a reference to the damage source, so your characters can react accordingly.
With a strategy like this, you can have just one simple damage-handling script that does just that one job (single-responsibility principle), rather than entangling AI behaviour logic in your damage taking code.
Your AI behaviour script(s) remain separate, and can be freely mixed-and-matched with this damage taking behaviour with zero code changes. In data, you can configure which AI behaviour(s) each enemy prefab should use, and which reaction method(s) should be called when it takes damage.
This is an example of the principle of composition over inheritance, allowing you to combine small modular components of code in remixable ways to produce lots of variety without hard-coding each combination, and without deep & inflexible inheritance trees. It's especially useful if you have non-programmers on your team, like game designers and level designers, because it empowers them to make and tune their own combinations without dependencies on code changes.
TakeDamage
code in all of their scripts. \$\endgroup\$Enemy
class. The baseEnemy
class will contain a virtualTakeDamage
method that you will override in the child classes. This way you can have a singleTakeDamage
method for each type of enemy that will first decrease their health as you have already done, and then perform an action that is unique to each individual enemy type. \$\endgroup\$