Unity 4.6 - Create A Energy / Health Bar HUD

In the previous post on Unity4.6, we saw How To Create A Dynamic / Responsive Menu. We will, in this post, continue to explore the all new Unity 4.6 UI features. Yes, we will create a Health / Energy Bar HUD! If you not gone through the previous post, I would recommend you to go through it.

Unity 4.6 - Energy Bar: The Result



Now then, let's get started.

1. Open the Play scene which you had created in the previous post. If you've not created the Play scene, create a New Scene and save it as Play, of course you can name it whatever you want.

2. Once you open the scene, you should have a Main Camera, I would suggest you to Position it at (0, 1, -15)

3. Add a Directional Light to the scene by navigating to Gameobject->Light->Directional Light. Position it at (0, 1, -15) as well.

4. Add a Cube to the scene from Gameobject->3D Object->Cube. Rename it as Player. Position it at (-1, 1, -10). Add a Rigidbody component to this Player and uncheck the Use Gravity checkbox.


 5. Create another Cube object and rename it as Fire. Position it at (2, 1, -10). Check the Is Trigger checkbox of the Fire's Box Collider component.


You can add a material to this Fire if you want, just like I did.

6. It is now time to add a Text UI component named Health, to indicate a Health Bar HUD.

7. Place the text so that it is visible on the top left corner of the Game screen. Make sure you move the anchor points with the text as well.



The above image shows you the things that I configured. You can follow it if you like or you can configure it the way you want.
1 signifies the position of the Health text
2 I have renamed the Text to HealthText.
3 Signifies the Position of the HelathText Rect Transform and also it's Anchor's min max positions. Also the Text content is changed to Health.
4 Best Fit is checked so as to make the Text dynamic. Max and Min size are set. Color of the font has been changed to White.
(Overlook the error in the console)

8. Create another Text element under the Canvas named GameOver. Position it wherever you want to with the anchor points placed at the four corners. Also check the Best Fit checkbox. Change the font color if you want to.

  
9. It is time to add a Slider, which will be used to indicate the Health of the Player. Place it besides the Health text and resize it as per your needs with the anchors placed around the corners.



10. We will disable the slider handle as we don't need it.


11. Change the Slider Fill color to Green


12. Create a C# script named MovementScript in the Scripts folder. Attach it to the Player GameObject. Open this script and add the below code to it.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class MovementScript : MonoBehaviour {

 public Slider healthBarSlider;  //reference for slider
 public Text gameOverText;   //reference for text
 private bool isGameOver = false; //flag to see if game is over

 void Start(){
  gameOverText.enabled = false; //disable GameOver text on start
 }

 // Update is called once per frame
 void Update () {
  //check if game is over i.e., health is greater than 0
  if(!isGameOver)
   transform.Translate(Input.GetAxis("Horizontal")*Time.deltaTime*10f, 0, 0); //get input
 }

 //Check if player enters/stays on the fire
 void OnTriggerStay(Collider other){
  //if player triggers fire object and health is greater than 0
  if(other.gameObject.name=="Fire" && healthBarSlider.value>0){
   healthBarSlider.value -=.011f;  //reduce health
  }
  else{
   isGameOver = true;    //set game over to true
   gameOverText.enabled = true; //enable GameOver text
  }
 }
}

- In the Start function we disable the GameOver text as we need it to be displayed only when the health is zero.
- The code above is very simple. The Update function gets input from the keyboard as long as the isGameOver flag is false. Press Right Arrow to move the Player to Right and Left Arrow to move it Left.
- OnTriggerStay function checks for contact between the Player and Fire object as long as the slider value is greater than zero. If the Player is in contact with the Fire, it's health will reduce at a rate of 0.01 units/frame. This value is reflected on the Slider. If the health value is zero, we will enable the GameOver text.
(Note: The slider value is set to 1 by default)

 
13. Save the script and return to Unity. Add the Slider and GameOver text elements to the script reference fields as below:


Now, your Health Bar HUD is all ready to be tested. Press the Play button to test your scene. Use the left and right arrow keys to move the Player.


See you around.

Also check out,
Unity 4.6 - Create A Level Select Scroll Menu
Unity 4.6 GUI - Create An Animated Menu
Share on Google+

About Sujit Horakeri

Sujit Horakeri is a game freak just like any other next door guy you would come across. He is a Web Developer by Profession, Game Developer by Choice.
Connect with him on:
    Blogger
    Facebook

10 comments:

  1. I get an error from the script and don't have script reference sections from step 13 showing anywhere

    ReplyDelete
    Replies
    1. Kindly be specific, let us know what error msg you getting in the console so that we can help you ...

      Delete
    2. You have an inconsistent name for the movement script.

      Step 12: "Create a C# script named PlayerMovement in the Scripts folder."

      But in the script it is referred to as MovementScript
      "public class MovementScript : MonoBehaviour {"

      May I ask that you update the page to prevent confusion which is the problem I suspect PsychitsMike has run into.

      Great clear tutorials otherwise, Bookmarked, I usually have trouble following tutorials unless they're in video form but this is very easy to follow so far. :)

      Delete
    3. Thank you notifying the error man.. Cheers!

      Delete
    4. Will you make a tutorial for health bars that follow enemies? Nobody seems to know a good way of doing it with uGui without having a canvas on every enemy, but that seems inefficient and a pain to work with since the giant canvas gizmos are all over the scene. Thanks

      Delete
  2. Hey, everything works, but the healtbar value doesn't move, when I touch the enemy. Does anyone know what I am doing wrong? Thanks!

    ReplyDelete
  3. Hello, Thank you very much for Your tutorials Im learning a lot following You.

    In this tutorial I did everything likr You but My health bar does not move when collides with the Fire object.

    Can You make a big favor and upload the package please!
    Thank you very much!

    ReplyDelete
  4. Thank you for the link but maybe instead of actually putting just a video of the end results perhaps you could actually put a tutorial for users to follow? Fifa 15 crack v4

    ReplyDelete
  5. Either can provide additional information on finding health insurance self employed alternatives.
    male edge extender

    ReplyDelete
  6. I am glad that I found your blog. Thanks for useful content. I also think you will be willing to read this post on whatsapp spy software.

    ReplyDelete