Unity RPG: Healthbars and damage mechanics

Step 1
Start by creating a canvas object
Step 2
This object is enormous in your game world and creates an EventSystem

The EventSystem is for detecting if the user clicks on any of the Canvas elements. Ignore it but do not remove it

Step 3
Set the Canvas to Scale with Screen Size
Step 4
Now right-click the Canvas in the hierarchy and create a Slider to use as a healthbar for the player
Step 5
Delete the slider background and handle. We won't need them

The handle would allow the user to slide the slider value back and forth (Not great for a healthbar!)

Step 6
Adjust the slider value up and down to see how it works for yourself

Leave the value at 1 before we start resizing and positioning the bar.

Step 7
Now focus on the canvas in the Scene view and position the healthbar in the upper left
Step 8
You can use the Scale tool to resize the healthbar
Step 9
Here's how you can change the color and transparency (alpha)
Check Your Work
Step 10
Check that you can adjust the Slider value and your bar changes and looks the way you want it to

Changing the Value of the Slider is all we need our Health Script to do...

Step 11
So, let's create a Script named Health

Notice we aren't calling this playerHealth. We will be able to use this Script for every object in our game which has health.

Step 12
Add the UI library to the top of the script

This let's us reference Sliders and Canvas elements

Step 13
Create a public reference to the Slider we'll be using and name it healthbar

Drag and drop the healthbar slider into this slot in the Inspector:

Step 14
Create a float for currentHealth and a *public* float for maxHealth
Temp1529106135 Temp1529106159

maxHealth needs to be public because different characters will have different amount of health, and we need an easy way to set that when the time comes

Step 15
Create a public function named TakeDamage

public so that other sources can tell our character to take some damage

Step 16
We'll need an input float to tell it *how much* damage to take
Step 17
Now we can subtract the *amount* of damage from *currentHealth*

TakeDamage(2) will subtract 2 from currentHealth
TakeDamage(10) will subtract 10 from currentHealth

Step 18
We now need to set the Value to a *percentage* of current and maximum health
Step 19
We can set the value of our slider using healthbar.value
Step 20
Right after changing the value of the health slider, play the "Hurt" animation

Use the following code to get started:


You'll need to:

  • Create a State and a Trigger for Hurt in the playerAC
  • Use the SetTrigger() method of the Animator
  • Create an Event at the end of the Hurt animation to call ReturnToMovement
Step 21
In the playerController, add a reference to the Health script. Name it "health" with a lowercase "h"
Check Your Work
Step 22
You can add this test code to make sure your function is working properly

It's a good idea to delete that test code once it works!

Step 23
Next, we're going to make the player take damage when hit by a projectile
Step 24
We'll be using the onCollisionEnter() built-in function to call Health.TakeDamage()
Step 25
Open the projectileController script which came with your RPG Assets folder

Find the OnCollisionEnter() function:

Step 26
Create a reference to the GameObject attached to the Collider that has been hit

We'll call that GameObject "other"

Step 27
Now we can get what we really want, which is the Health Script of that object
Temp1529957727 Temp1529958069

If the object we hit does not have a Health script, "otherHealth" will be equal to null

Step 28
If the object hit *does* have a Health Script, tell it to Take 2 Damage
Check Your Work
Step 29
Now get hit by a rock and check that your health goes down by 2
Step 30
Now we'll actually want to use a variable so we can set the damage for each type of projectile in our game

Here we create a public float damage with a default value of 1:


Different projectiles you make can be set to deal different amount of damage by changing this value in the Inspector:

Step 31
Set the damage of the rock *prefab* to 2
Check Your Work
Step 32
Verify that your project works the same as it had before this change
Step 33
Inside of the TakeDamage function have it SendMessage that the script parent has died if currentHealth < 0
Step 34
SendMessage("onDeath") tells every component on the GameObject to run a function named "onDeath"
Step 35
In the playerController create an "onDeath" function and have it Log "Broken!" to the console
Check Your Work
Step 36
Test that the player logs "Broken!" to the console when their health is depleted

You may want to temporarily set the rock damage to 10 so the player's health is depleted in 1 hit:

Step 37
Now create a new State named "Break" which plays the "Break" Animation Clip on the player

We're going to transition this State out of the Any State node

Step 38
Remember to add a return path to the "Movement" State
Step 39
Now set up the Events and Transitions so that when you rewrite the onDeath function below, the player will break

The Break Animation clip will need an Event which calls ReturnToMovement

Check Your Work
Step 40
Check that the player plays the Break animation upon running out of health
Step 41
This is a good time to add a quick checkpoint mechanic

We'll set a checkpoint variable when the game starts

Step 42
We'll also need to add a public Reset function to the Health Script
Step 43
And now we can call a ReturnToCheckpoint function as an Event call at the end of the "Break" Animation

This function will need to perform three tasks as written below:

Temp1529966568 Temp1529966750
Check Your Work
Step 44
Now verify that after Breaking, the player is sent back to the start with a full healthbar and can move again
Step 45
We can fix a small error by having TakeDamage only trigger "Hurt" if the GameObject is not dead
Check Your Work
Step 46
Check that the player does not flinch after the Break animation
Step 47
Next we'll add a tiny healthbar to the enemies. (We'll be using the same Health script we just made)
Step 48
Right-click the rockSpitter and create a Canvas as a child object
Step 49
Set this Canvas to use World Space

World Space means it exists inside the game world, rather than ontop of the screen.

Step 50
Make this Canvas very tiny with a width and height of around 1

Set the Y-Rotation to 180, otherwise everything will be backwards


The blue arrow should be pointing behind the rockSpitter.

Step 51
Now right-click this canvas in the hierarchy and create a new Slider

It's going to be very large!

Step 52
Delete the slide handle
Step 53
Copy these values for the Slider dimensions
Temp1529970998 Temp1529971165
Step 54
...And these values for the Fill Area
Temp1529971521 Temp1529972396
Step 55
...Lastly these values for the Fill
Temp1529971692 Temp1529972530

We're also removing the Source Image:

Temp1529972549 Temp1529972562
Step 56
Now you can set the color of this bar however you wish
Temp1529971822 Temp1529972586
Step 57
And here we set the Transform of the Background object
Temp1529972773 Temp1529972811
Step 58
You can pick a darker color for the Background
Step 59
Now it's time to make the Beamsword call the TakeDamage function of the rockSpitter

We need to design a hitbox to detect collision

Step 60
I found the values for my hitbox by creating a Cube and positioning it in the Inspector
Temp1529977972 Temp1529978050

It's good to make the hitbox very large rather than to try to make it accurate:

Step 61
Here are the dimensions I came up with for a good hitbox size
Step 62
And here is it's position relative to the player

You can now delete the Cube as we just made it so we could get these values.

Step 63
We'll be using Physics.OverlapBox to check for collisions inside of this hitbox

The OverlapBox function needs a center and then the half-extents (half-width, half-height, and half-depth)

Step 64
So, let's create a DealWeaponDamage function in the playerController
Step 65
First we calculate the center

Remember we need 1 step in front of the player, and 1 step up from the player

Step 66
Now we record the halfExtents in a Vector

Remember we had a:

  • width of 1
  • height of 2
  • depth of 1

So the halfExtents would be (0.5, 1, 0.5)

Step 67
Now we can create an array of every collider touched by the OverlapBox at position "center" with size "halfExtents"

Here we also set the rotation of the box to the player's rotation

Step 68
Everything Overlapped by this box will be stored temporarily in this array "hits"
Step 69
So we say: For every "hit" in the "hits" array...

We need to get the Health script (if it has one) and tell it to take damage

Step 70
Use GetComponent to try to get the Health Script of anything hit by the box
Temp1529979972 Temp1529980144
Step 71
If it successfully finds a Health Script, tell it to take 1 Damage
Step 72
Now create an Event in the player's Swing animation, right after the sword arc completes, to call this function
Step 73
Before we can test you'll need to add a rigidbody and a collider to the rockSpitter

Be sure to Turn off Gravity and make the rigidbody Kinematic!

Kinematic means it is not effected by outside forces.

Check Your Work
Step 74
Check that the rockSpitter loses health and that its bar depletes when hit by the overlapBox
Step 75
Set up the rockSpitter to play the Hurt animation from Any State
Temp1529981871 Temp1529981911

Remember that the TakeDamage function sets the "Hurt" trigger (which so far you don't have for the rockSpitterAC) already!

Check Your Work
Step 76
Check that the Hurt animation plays upon striking the rockSpitter
Step 77
Now give it an onDeath function (remember the Health Script attempts to call this function when health <= 0)

When the spitter loses all of its health we'll have it Destroy itself after 2 seconds


This gives it time to play its hurt animation before destroying itself.

Step 78
Click Apply to apply all of these changes to the rockSpitter prefab
Step 79
Now you can set a bunch of them around your Scene
Check Your Work
Step 80
Check that you can fight and defeat them all!
Unity RPG: Healthbars and damage mechanics Info


MVCode Clubs

Created By

Newprofile jamie


Build an RPG in Unity

Access Level


For Teachers and Schools

Teach coding to your students with MVCode Teach

MVCode offers an integrated product designed to teach coding to students.

Learn more about MVCode Teach