3D Survival FPS Game
Now that we have our Ray Cast and Enemy movement done, it is time to add the universal Health script. Although there are better methods of doing a health function, such as interfaces and abstract classes, for this game we are going to be doing a more simple version.
Start by creating a new C# script and name it “Health”. We are going to be attaching this script to both the player and enemy game object since this will be based on an Universal health system.
Next we are going to create 3 global variables one for minimum Health, one for maximum Health and one for current Health.
We are going to add the Serialized Field to them because we want the ability to adjust the total values within the inspector. This is also crucial because each value is going to be different when the health script is applied to different objects. That means both the Player and Enemy can both have different values of health even thought they use the Health script.
Within the Start method we are going to address the current health as maximum health. This way, all players and enemies start out with full health at the start of the game.
What is health points without a method to make sure of them. Time to create a damage method which will allow the player to destroy the enemies.
Within the same Health script we are going to create a new public method called “Damage”. It is public because we want other scripts such as the player to be able to gain access to it.
Inside this public method we are going to basically toggle the subtraction of current health with the incoming damage. Then when the current health is below the minimum health value, we will delete the object.
To apply this damage method, we are going to use the Shooting script where we haven’t really finished our shot method. Currently we just have a Debug function, but now we can actually gain access to the damage method and make use of it.
When trying to gain access to the correct Health script. Since both the player and enemy both have the same script we are going to rely on the hit Info collider. Therefore we are only tracking whatever game object the Ray cast targets. If that target gets an health value they are going to get damaged. But what happens when an object that gets hit by the Ray cast doesn’t have a health script. This is were we must null check to omit the error and still have the script functional.
So using the IF statement, we check if the health script is attached to the object the Ray cast has attached to. If there isn’t any health script then nothing happens, vice versa if there is an health script we will call upon the health damage method and pass in a damage amount.
Back in Unity, within the inspector you will noticed that the health values are now present and can be set individually among different game objects.
This is a very simple and yet effective modular health system that is applied to this game, although limited it serves its function for this prototype.