Home and Learn: Games Programming Course


Increasing the Player's Health

In previous lessons, we got the zombie to attack the player. The player's health score decreased. We displayed the player's health on screen. In this lesson, you'll learn how to implement a health pickup system. When a health pack is picked up, the player's health will increase.

For this, we'll have a health icon somewhere in the scene. We'll have it so the player just has to walk through the health icon to get the points increase. It will look like this:

Unity Game showing a health icon

The green cross is easy to create.

Right click in your Hierarchy on the left of Unity. From the menu that appears, select Create Empty. Name the empty game object HEALTH_ICON. In the Inspector on the right, set the Scale X, Y, and Z to 0.5.

Now right click HEALTH_ICON. From the menu, select 3D Object > Cube. In the Inspector, make sure the Position and Rotation are all 0. For the Scale, set the X and Z to 1 and the Y to 3. Now right click your new Cube. From the menu, select Duplicate (you can also press CTRL + D on your keyboard). Change the Z Rotation to 90. Your Hierarchy should look like this:

The Unity Hierarchy showing an empty game object with 2 cubes underneath it

(You won't have the three items above HEALTH_ICON - we're doing a zombie spawner next. Stay tuned!)

Now create a material for your health icon. In the projects area at the bottom of Unity, create a Materials folder for yourself, if you haven't already done so. Inside of your Materials folder, right click and select Create > Material. In the Inspector on the right, change the Base Map color from the default grey to anything you like. We went for green.

Once your material is created, drag and drop it from your Material folder onto the two cubes in your scene. Job done, and it should look like ours at the top of this lesson. But move your HEALTH_ICON to wherever you want in your scene, whatever place you feel is best for a health pickup.

 

HEALTH_ICON Components

Select your HEALTH_ICON empty game object in the Hierarchy on the left. In the Inspector on the right, add a Box Collider Component. Check the box for Is Trigger. And set the size to these values:

Size X: 3
Size Y: 3.5
Size Z: 3

Your HEALTH_ICON icon should look like this:

A Box Collider game object showing in the Unity Inspector

Now, click the Add Component button again. This time, add an Audio Source. Download this simple sound:

Health Pickup Audio (106KB WAV file)

Drag and drop the wav file into the Assets folder of your game. Once it's in your assets folder, drag it onto the Audio Resource slot in the Inspector. Uncheck Play on Awake and it should look like this:

An Audio Source added to a Unity game object

Now for the Health Pack Script. It's quite short.

Again, click the Add Component button. Select New Script. Name your script HealthPack. Click Create and Add. When the new script is added, double click its name in the Inspector to open it up in your code editor. Delete the entire contents of the script. Copy and paste this instead:

using UnityEngine;

public class HealthPack : MonoBehaviour
{
	public static bool hasPickedUpHealthPack = false;
	private AudioSource health_pack_sound;


	private void Start()
	{
		health_pack_sound = GetComponent<AudioSource>();
	}

	private void OnTriggerEnter(Collider other)
	{
		if (other.CompareTag("Player"))
		{
			hasPickedUpHealthPack = true;
			health_pack_sound.Play();

			Destroy(gameObject, 0.1f);
		}
	}
}

Save your work. Don't go back to Unity just yet as we need to amend the Player Health script. But your HealthPack script should look like this:

Unity C# script for a health pack

The scripts sets up two variables at the top. The first is a public static bool called hasPickedUpHealthPack. It's static because we want to access this from the player health script. The second variable is the for the audio source, so we can play a sound. We get a reference to this in the Start method.

The only other code is inside the OnTriggerEnter method. We did this in a previous lesson. It gets activated because we set Is Trigger on the box collider to true.

But we just Compare the Tag of the object that enters the trigger. If it's the Player, then we can set hasPickedUpHealthPack to true. We Play the sound and then Destroy the health pack:

Destroy(gameObject, 0.1f);

Notice the 0.1f at the end. We can't set it to zero as the sound won't play - the object will be destroyed before the audio source can kick in. Setting Destroy to a low value means the audio source has enough time to play.

Now for the Player script.

 

Player Health

Load up PlayerHealth in your code editor. (If you can't find it, it's attached to your Player game object. Select it in the Hieararchy. In the Inspector on the right, double click the name of the PlayerHealth script.) In your Player Health script, add a new variable at the top:

public int healthPackValue = 100;

Now copy and paste this Update method:

private void Update()
{

if (HealthPack.hasPickedUpHealthPack)
{

currentHealth = currentHealth + healthPackValue;
HealthPack.hasPickedUpHealthPack = false;

if (currentHealth > maxHealth) {

currentHealth = maxHealth;

}

UpdateHealthUI();

}

}

You don't need to touch anything else in the script. But it should look like this your editor (the highlighted lines are the ones to add - lines 10 and lines 20 to 34):

Unity C# script for a player's health

(If you haven't got the whole of the player's health script yet, here it is in its entirety Player Health Script - Opens in new window)

The Update method gets called by Unity constantly. We first check if that static variable from the HealthPack script, hasPickedUpHealthPack, is set to true:

if (HealthPack.hasPickedUpHealthPack)

Inside of the if statement, we set the currentHealth to the value of the health pack:

currentHealth = currentHealth + healthPackValue;

We set a value for the healthPackValue variable to 100. But you can set it to anything you like. Whatever you think a health shot increase should be.

We then set hasPickedUpHealthPack back to false, just so it doesn't trigger again:

HealthPack.hasPickedUpHealthPack = false;

The other if statement just keeps the player's health at the maximum.

Finally, we update the health UI on screen:

UpdateHealthUI();

Save your scripts and go back to Unity. If you look at the Inspector for your Player, you should see a Health Pack Value added to it, something you can change here in the Inspector:

A Player Health script showing in the Unity Inspector

One final thing we can added is some rotation and movement just to liven the health pack up. Try this.

Add a new script to your HEALTH_ICON. Call it RotateHealthPack. Open the script in your editor. Delete the entire contents of the script. Copy and paste the following: (It a little complicated and we won't go through it.)

using UnityEngine;

public class RotateHealthPack : MonoBehaviour
{
	public float rotationSpeed = 50f; //Rotation speed

	public float hoverSpeed = 2f; // Speed of the hover movement
	public float hoverHeight = 0.2f; // Distance it moves up and down

	private Vector3 startPosition;
	private float targetY;

	void Start()
	{
		startPosition = transform.position; // Store the initial position
		targetY = startPosition.y;
	}

	void Update()
	{
		transform.Rotate(Vector3.up, rotationSpeed * Time.deltaTime);

		float desiredY = startPosition.y + Mathf.Sin(Time.time * hoverSpeed) * hoverHeight;

		//SMOOTH OUT MOVEMENT WITH LERP
		targetY = Mathf.Lerp(targetY, desiredY, Time.deltaTime * hoverSpeed);
		transform.position = new Vector3(transform.position.x, targetY, transform.position.z);
	}
}

It should look like this in your editor:

A Unity C# script to rotate a game object

Save your work and go back to Unity. Your Inspector should look like this:

Unity Inspector showing a C# script to rotate a game object, changeable values are displayed

You can adjust the rotation speed here, as well as the hover speed and hover height.

Play your game and it should look like this:

 

Improvements

You can improve the health icon by using a better sound and perhaps adding a particle effect. You can get some ready-made particles in the Unity Assets store (Window > Asset Store). Do a search for unity particle pack. Try some by instantiating a particle game object in your HealthPack script:

public ParticleSystem pickupEffect; // Add this at the top

Change your OnTriggerEnter code (the line to add is in bold):

if (other.CompareTag("Player")) {

hasPickedUpHealthPack = true;
health_pack_sound.Play();

Instantiate(pickupEffect, transform.position, Quaternion.identity);

Destroy(gameObject, 0.1f);

}

You can drag a particle effect onto the empty pickupEffect slot in the Inspector. (If this doesn't work, you may have to first drag and drop a particle prefab onto the HEALTH_ICON item in the Hieararchy. Then drag that particle from the Hierarchy onto the empty pickupEffect slot. Finally, uncheck the box at the very top of the Inspector for your prefab, just to deactivate it.)

 

But we'll move on. At the moment, our 1 zombie in the scene looks a little lonely. In the next lesson below, we'll add some more zombies by prefabbing the one we have.

<--Back to the Unity 3D Course Contents Page

 


Email us: enquiry at homeandlearn.co.uk