Player Death & Damaging Functions

Kenny Pruitt
Unity Coder Corner
Published in
3 min readMar 2, 2023

Objective: Player Death & Damaging Functions

Now that I have a health system, I can begin creating a damage system for the player and enemies. An easy and adjustable way to do this is to create a function called AdjustHealth(float adjustmentValue).

The float value inside of this function makes it so if something is going to adjust the health, it will require a value of how much to adjust the health by. In order to use this function properly, we can simply say currentHealth += healthValue.

This will always add to the current health and adjust it. For example if the player was hit by the enemy and you want to deal 25 damage, you would simply call the function like this AdjustHealth(-25).

We can also use this method for gaining health back as well, simply by calling AdjustHealth(25). Since we will be adjusting the players health, we also must make sure there are limits placed on max health and when the player reaches 0 then the player is dead and is destroyed. To limit the max health, we can simply make a variable for the max health, then compare it to the current health and if the current health is greater than max health, then just make the current health equal the max health.

If the player’s health reaches 0 on the other hand, we need to destroy the player.

Then we can add a little explosion effect so when the player dies it will be a visible occurrence, to do so we can simply make a particle effect prefab and add it to our script.

Then let’s also add a color change effect to the player material, so it flashes red when hit. To do this we can create a Coroutine that changes the player’s color, then after 0.1 seconds it reverts the player back to the default player material.

Once the player is destroyed, we want to make sure the enemy spawns stop, so in order to do so, before we destroy the player, we can get the EnemySpawner component, by using FindObjectWithType<EnemySpawner>(). Once we have reference to the spawner, then we can simply set the disableSpawner bool to true and it will close out the Coroutine that is spawning the enemies.

To clean this code up a little, we can add our own PlayerDied() function as well.

Now we can go back and test in Unity.

--

--

Unity Coder Corner
Unity Coder Corner

Published in Unity Coder Corner

UCC is the one stop shop for everything Unity3d. From tutorials, to news, to opinon pieces. Find everything related to Unity3d here.

Kenny Pruitt
Kenny Pruitt

Written by Kenny Pruitt

Unity Game Developer, C# Developer, and Software Engineer