Unity RPG: Healthbars and damage mechanics

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

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
Temp1529104627
Step 4
Now right-click the Canvas in the hierarchy and create a Slider to use as a healthbar for the player
Temp1529101232
Step 5
Delete the slider background and handle. We won't need them
Temp1529101446

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
Temp1529103509

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
Temp1529105465

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
Temp1529983769

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
Temp1529105626

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

Temp1529984483
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
Temp1529106608

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
Temp1529106739
Step 17
Now we can subtract the *amount* of damage from *currentHealth*
Temp1529106836

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

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

Use the following code to get started:

Temp1529106915

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"
Temp1529107975
Check Your Work
Step 22
You can add this test code to make sure your function is working properly
Temp1529985460

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

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

Find the OnCollisionEnter() function:

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

We'll call that GameObject "other"

Temp1529957660
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
Temp1529958486
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:

Temp1529959101

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

Temp1529959511
Step 31
Set the damage of the rock *prefab* to 2
Temp1529960102
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
Temp1529963787
Information
Step 34
SendMessage("onDeath") tells every component on the GameObject to run a function named "onDeath"
Temp1529964253
Step 35
In the playerController create an "onDeath" function and have it Log "Broken!" to the console
Temp1529964304
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:

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

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
Temp1529965924
Challenge
Step 39
Now set up the Events and Transitions so that when you rewrite the onDeath function below, the player will break
Temp1529966073

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

Temp1529966259
Step 42
We'll also need to add a public Reset function to the Health Script
Temp1529966983
Challenge
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
Temp1529967312
Check Your Work
Step 46
Check that the player does not flinch after the Break animation
Planning
Step 47
Next we'll add a tiny healthbar to the enemies. (We'll be using the same Health script we just made)
Temp1529969916
Step 48
Right-click the rockSpitter and create a Canvas as a child object
Temp1529969999
Step 49
Set this Canvas to use World Space
Temp1529970051

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
Temp1529970286

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

Temp1529970305

The blue arrow should be pointing behind the rockSpitter.

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

It's going to be very large!

Temp1529970561
Step 52
Delete the slide handle
Temp1529970615
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
Temp1529972619
Planning
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

Temp1529977947
Information
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:

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

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

Planning
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)

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

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
Temp1529981204

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"
Temp1529979393

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

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

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
Temp1529980200
Step 72
Now create an Event in the player's Swing animation, right after the sword arc completes, to call this function
Temp1529980675
Step 73
Before we can test you'll need to add a rigidbody and a collider to the rockSpitter
Temp1529980305

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
Challenge
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

Temp1529981948

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
Temp1529981996
Step 79
Now you can set a bunch of them around your Scene
Temp1529982095
Check Your Work
Step 80
Check that you can fight and defeat them all!
Unity RPG: Healthbars and damage mechanics Info

Account

MVCode Clubs

Created By

Newprofile jamie

Course:

Build an RPG in Unity

Access Level

premium

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