Pioneered in some of the world’s earliest video games, health is a common mechanic that carries over into many of today’s most popular titles. Health allows for complex combat mechanics, crafting player progression, and making the game more intuitive. But how do you add a health system to your game?
Unity3D makes it easy to add 2D UI elements to your 3D game, so it’s a great place to start exploring health bars for the first time.
content of study
On the surface, this project may not look complicated. Still, you need to understand some core Unity3D coding concepts to create a valid health bar. This means that there is a lot to learn through this project.
- How to create 2D UI elements/sprites in Unity3D.
- How to edit game object components in code.
- How to share variables between scripts in Unity3D.
Step 1: Set the Scene
Before we start coding our health bar, we need a scene with a player model to apply it to. To get started, follow his physics-based Unity3D character controller guide to create a player model with basic controls.
With the scene and player model in place, it’s time to add the UI elements. Right-click inside the Hierarchy window and select UI > imageThis creates two new items in the hierarchy, a Canvas parent object and an Image child object. Rename the child object to Healthbar. Use the inspector to choose the width, height, and position of the health bar.
You can add a slightly larger UI image with color set to black to act as a background/border for the health bar. Make sure it’s above the health bar in the hierarchy so it appears behind it.
This UI element serves as the basis for the health bar, but we also need a sprite to animate it. Go to your project pane, right click, create > Two dimensions > sprite > square.
Select Healthbar from the hierarchy and drag the sprite you just created onto the source image selection box in the inspector.You can also change Image type filled, Fill method horizontally and fill origin to the left.run the game Loading You should see the health bar shrink and expand as you move the slider.
If you don’t see the UI component menu, Window > Package Managermake sure the 2D pack is installed.
Step 2: Add Health Variables
It doesn’t make much sense to create a health bar without putting a health variable to dictate the state. Other scripts need to be able to access this variable, so it makes sense to put it in a central location. Add this to your Character Control script as a public float.
public float playerHealth = 1.0f;
Using a float for this variable makes it easy to represent any percentage between 0 and 100, matching the Fill Amount variable in the health bar UI image. For example, a playerHealth of 0.5f is 50% of the width of the health bar.
Step 3: Share variables between scripts in Unity
Variables typically work within their own functions and scripts. This makes them inaccessible to other functions and scripts unless you take steps to tell your code where to work with variables.
First, create a new script file named Health to contain your code. You can drag and drop this script onto the Healthbar UI element created in the first step. The following code goes into the void Update() function.
The process begins by finding the game object that owns the variable. In this case, it’s a Character_Model object.
GameObject Character_Model = GameObject.Find("Character_Model");
Then find the script component that contains the variable you need to manipulate.
Character_Control character_Control = Character_Model.GetComponent();
Finally, you can extract the specific variable you’re looking for. In this case, it’s the playerHealth variable we added to the character controller. Assign this to a float variable in the current script called currentHealth.
currentHealth = character_Control.playerHealth;
It takes only a few lines of code to get the variables we need and we can apply this method whenever we need to access the player’s health. When you’re done, your code should look like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class Health : MonoBehaviour
{
public float currentHealth;
void Start()
{
}
void Update()
{
GameObject Character_Model = GameObject.Find("Character_Model");
Character_Control character_Control = Character_Model.GetComponent();
currentHealth = character_Control.playerHealth;
}
}
Step 4: Program the UI Health Bar Game Object
Now that you have created the health bar UI element and have access to the player’s health variables, it’s time to make them work together. First, add a private static variable containing the health bar image component.
private static Image Healthbar;
You can then assign the image component to this variable within the void Start() function, which runs only once.
Healthbar = GetComponent();
With all the variables in place, we can use the code from the previous step to set the fill width of the health bar UI object. No need to perform any conversion here. Both player health and health bar fill amount are float variables.
Healthbar.fillAmount = currentHealth;
Placing this code will raise or lower the health bar based on the health variable found in the Character_Control code. However, this is a little boring. You can definitely use some colors.
First, we’re adding a new color to make the health bar bright green when the player has high health.
Color greenHealth = new Color(0.6f, 1, 0.6f, 1);
Next, add an if statement to check if the player’s health is above 0.3f, or above 30%. If it’s higher than 0.3f, set the health bar to match the color you just added. If it’s less than 0.3f, make the health bar red.
if (currentHealth >= 0.3f) {
Healthbar.color = greenHealth;
} else {
Healthbar.color = Color.red;
}
Step 5: Test Your Code
As you can see from the full code below, this project is pretty simple when everything is put together. Of course, you need a way to test your code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class Health : MonoBehaviour
{
private static Image Healthbar;
public float currentHealth;
void Start()
{
Healthbar = GetComponent();
}
void Update()
{
GameObject Character_Model = GameObject.Find("Character_Model");
Character_Control character_Control = Character_Model.GetComponent();
currentHealth = character_Control.playerHealth;
Healthbar.fillAmount = currentHealth;
Color greenHealth = new Color(0.6f, 1, 0.6f, 1);
if (currentHealth >= 0.3f) {
Healthbar.color = greenHealth;
} else {
Healthbar.color = Color.red;
}
}
}
You can add one line of code to the Character_Control script to enable testing. Removes a small amount of health each time the player presses his W key to move forward. You can add the same code to any script that has access to the playerHealth variable to achieve the same result.
playerHealth -= 0.001f;
You can also consider adding your own assets to your Unity project. You can find free Unity assets on the web to spice up your project without spending a dime.
Create a health bar in Unity3D
Now that your character’s health bar is set, the game is starting to take shape. You still have a lot of work to do, but you should have some key skills you need to really make progress. Of course, it doesn’t hurt to read more guides.