Unity Development — Modular Health
In general, when coding the user controlled Player and the computer controlled enemies, they would have very little in common. Sometimes, however, you can still save some time by finding something common and making sure not to code it twice.
In this example, both our Player and the Enemy have health and can have some of that health damaged. To keep up with the principals of object oriented programming, we will have a separate class/script specifically for health and damage that will go on both objects.
Right away we declare a max health, min health, and current health. They are serialized, so that they can be given different values to the different objects. At the beginning for the scene, the current health is set to the max health as well. Now we’ll make a public Damage() function.
Since this function is public, we can call it from anywhere we get a reference to the object and the Health script. The Player has a shooting mechanic with a Raycast. If it hits an Enemy, it can search for the Health script. If it isn’t null, it can perform the Damage function.
The same goes for the Enemy. It has a reference to the player and thus can call on the Health script and Damage() as long as it isn’t null, in a completely separate circumstance.
And that’s really all there is to it. There are other ways to do this. Interfaces is a good example, but that is one for another day.