Gaming in Unity

09. Unity 2D Game 5 - Health Collectible

(../img/unity-9-2d-game-5-health-collectible/2d-game-5-health-collectible-header.png)

This guide will show how to add a Health Collectible!

Step 1 - Adjusting SpriteController script

Open SpriteController script.

We're going to add two new variables and a property:

public int maxHealth = 4;
public int health { get { return currentHealth; }}
int currentHealth;

The middle line (a property) allows health to be accessed by other scripts.

In void Start(), set health to maxHealth.

currentHealth = maxHealth;

And now add a function called public void ChangeHealth(int amount)

Within void ChangeHealth, add the following:

currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
Debug.Log(currentHealth + "/" + maxHealth);

This function changes currentHealth by an amount whilst ensuring that health stays between 0 and maxHealth.

SpriteController should now look like this:

(../img/unity-9-2d-game-5-health-collectible/2d-game-health-collectible-step-1.jpg)

Import Heart.png into Assets -> Environment.

Drag this into Scene. Adjust the scale down and place it somewhere.

Add a Box Collider 2D to the GameObject and resize it to fit better.

Now, SpriteCharacter will collide with Health Collectible.

Next, enable the Is Trigger property in the Box Collider 2D component.

(../img/unity-9-2d-game-5-health-collectible/2d-game-health-collectible-step-1-2.jpg)

Step 2 - Creating Collectible Script

Go to Assets -> Scripts.

Right-click and select Create -> C# Script.

Name this script HealthCollectible.

Drag-and-drop the HealthCollectible script onto Heart in the Hierarchy.

Open the HealthCollectible script.

Delete the Start and Update functions.

We need to add code to detect when SpriteCharacter collides with the object and then add health to the Character.

Add the following function:

void onTriggerEnter2D(Collider2D other)
{

}

This will detect when a sprite collides with the Heart.

Next, we need to access the SpriteController script of the Character when it enters the Trigger:

SpriteController controller = other.GetComponent<SpriteController>();

Next, we need to check whether the Sprite that's colliding is the main character and not an enemy:

if(controller != null)
{

}

Inside this, we're going to add another If statement to check whether SpriteCharacter's health is below maxHealth:

if(controller.health < controller.maxHealth)
{

}

And now we add code into this that will add health to the character and remove the heart from the scene.

controller.ChangeHealth(1);
Destroy(gameObject);

(../img/unity-9-2d-game-5-health-collectible/2d-game-health-collectible-step-2.jpg)

Press play and move SpriteCharacter into the Heart. The Heart should disappear and a message appear in the console indicating health has increased to 3/4!

(Don't forget to turn Heart into a prefab by dragging it from Hierarchy into Assets -> Prefabs)

Created by: David Corish