Home and Learn: Games Programming Course


Unity 3D: Display the Player's Health On Screen

At the moment, we're only displaying the player's health in the console via a Debug line. Which is no good for a game. What we'll do now is to display the health on screen using user interface elements. Let's add a Text Component.

 

Unity Text

In the Hierarchy on the left, expand your MainCamera item. This is where you have your player's gun and the gun sight. We can add a User Interface (UI) element here, as well. So, right-click on MainCamera. From the menu, select UI > Text - Text Mesh Pro:

Unity context menu showing the UI > Text Mesh Pro item highlighted

(If this is this first time you're adding Text Mesh text to a project, you'll see a dialog box appear asking you to import Text Mesh Pro. Go ahead and do this. But Text Mesh Pro just gives you more formatting options than the other Text on the menu above.)

Rename your new TextMesh Pro item. Call it Text-Health:

Adding a Text Mesh Pro item to a game object in the Unity 6 Hierarchy

In the Inspector on the right, delete New Text from the Text Input box. In its place, type Health 100:

The Text Input box for a Text Mesh Pro game object

In scene view, it will look like something like this, once you zoom out:

A Text Mesh Pro item added to a Unity Scene

You can drag the green arrow up, and the red arrow to the left or right to reposition your text. Or just type some values for Pos X and Pos Y in the Inspector on the right. The top half of Inspector looks like this for us, as we have positioned our text in the top left:

A Text Mesh Pro component in Unity 6 with the Rect Transform values highlighted

Switch to the game tab to see this:

Game view in Unity 6 showing health text in the upper left

If you scroll down a bit in the Inspector, you'll see lots more settings you can apply to your text:

Text Mesh Pro font settings

The default font size is 36. You can make this bigger or smaller, if you want. If you do, you may need to change the Width and Height in the Rect Transform area. The default font color is white. You can change this to anything you like. The default font is Liberation Sans. Take a look at the other font options:

Selecting a font to use for Text Mesh Pro

You could import a font as an Asset, if you wanted to. If you do, the font will show up on the list. Try the fonts out, though, and see what they look like.

You can also choose a different Text Style. Click the dropdown to see a list of inbuilt styles:

Text Mesh Pro in-built font styles

Again, try them out to see what they look like. We'll keep ours on Normal.

There are lots of other options you can explore for the font. Take a look at the Font Style icons, for example. You can have Bold, Italic, Underline, Strikethrough, Lowercase, Uppercase, and Small Caps.

 

Health Code

Now go back to your PlayerHealth script. You can delete all the code and copy and paste the following. Or just add the highlighted lines (the green comment lines). Here's the new code:

using UnityEngine;

public class PlayerHealth : MonoBehaviour
{
	public int maxHealth = 100; 
	private int currentHealth;

	//==================================
	public TMPro.TMP_Text healthText;
	//==================================

	void Start()
	{
		currentHealth = maxHealth;

		//===================
		UpdateHealthUI();
		//===================
	}

	public void TakeDamage(int damage)
	{
		currentHealth -= damage;
		Debug.Log("Player Health: " + currentHealth);

		//===================
		UpdateHealthUI();
		//===================

		if (currentHealth <= 0)
		{
			Die();
		}
		else {
			Debug.Log("HEALTH= " + currentHealth);
		}
	}

	//==============================================
	private void UpdateHealthUI()
	{
		if (healthText != null)
		{
			healthText.text = "Health: " + currentHealth;
		}
	}
	//==============================================

	private void Die()
	{
		//=============================
		healthText.text = "DEAD! ";
		//=============================

		Debug.Log("Player has died!");
		// Add stuff here: respawn player, Game Over Screen, etc
	}
}

And here's what your coding window will look like:

There's not much to the code. We set a public variable called healthText. It is of type TMPro.TMP_Text. Then we add a method called UpdateHealthUI. This first line checks to see if the healthText object isn't null. Then we access the text property to update the current health:

healthText.text = "Health: " + currentHealth;

The new method is called in two places, once in the Start method and once in the TakeDamage method. We also update the text on screen when the player dies.

Save your code and go back to Unity. Select your Player item in the Hierarchy. Drag and drop the Text-Health item onto the empty slot, Health Text in the Inspector on the right:

The Player game object showing a Health Text script in Unity 6

(Instead of dragging and dropping from the Hierarchy, you can click the small circle indicated by the red arrow in the image above. Then select your Health Text from the dialog box that appears.)

 

Play your game. When you get hit by the zombie, you should see the player's health decrease on screen.

(Instead of text to record the player's health, you can have a Health Bar. We have a tutorial for that here on our site Health Bars. You'll need to adapt the script a little, though.)

In the next lesson below, let's give the player the ability to increase health.

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


Email us: enquiry at homeandlearn.co.uk