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.
    Blogger
    Facebook

51 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
  7. At the end of that year, the cost for the plans is going to go up in 2015. I can guarantee that that's going to happen, because the young healthy people are not going to be motivated to get into the plans.modafinil

    ReplyDelete
  8. Thanks for sharing helpful information, I really like your all post. I will bookmark your blog for future updates Send Gift To Pakistan

    ReplyDelete
  9. That’s so nice. I really like this. Thank you for sharing Send gift to Pakistan online.

    ReplyDelete
  10. In the event that you think it isn't the situation with your scope simply quit perusing this since it will be only midriff of your opportunity. Orlando Insurance

    ReplyDelete
  11. . Be that as it may, practice isn't the best way to assemble that body delightful. It likewise involves certain measure of obligation on the nourishments one eats. clenbuterol effects

    ReplyDelete
  12. Thanks for sharing these useful information! hotmail login account

    ReplyDelete
  13. With so many to choose from, you will have to take out the time to research about their qualification labiaplasty toronto

    ReplyDelete
  14. The absolute most basic health advancement exercises are smoking lessening exercises, healthy sustenance or physical exercise projects, aversion and decrease of medication and liquor manhandle. Methyl-Life

    ReplyDelete
  15. Prohibit anyone from deviating from the defined meaning when reporting services rendered (providers, suppliers) and adjudicating claims for payment (payors and others). Make violations a strict liability issue.fitness equipment for sale

    ReplyDelete
  16. Professionals regularly guarantee that these sorts of advantages happen, however almost no examination has inspected this probability. Food

    ReplyDelete
  17. Investigation of human conduct is critical in general health and in any network situated program. Link

    ReplyDelete
  18. This explains why people sometime die without any sort of outward sickness or pains. The issue is that, we think a sick person must be under some kind of pains.waist to height ratio

    ReplyDelete
  19. An essential distinction among traditional and elective drug is that while regular solution targets particular manifestations and their causes, Alternative Health Care has an all encompassing approach;that is to state it treats the entire individual, somatropin hgh injections

    ReplyDelete
  20. You delivered such an impressive piece to read, giving every subject enlightenment for us to gain information. Thanks for sharing such information with us due to which my several concepts have been cleared. phenq before and after

    ReplyDelete
  21. What can be done about the challenges? How can we as individuals contribute to the solutions?here

    ReplyDelete
  22. Medicaid - This is a government or s state open help program made in the year 1965. These are accessible for the general population who may have inadequate assets to pay for the health care administrations or for private insurance approaches.psicoterapeuta avezzano

    ReplyDelete
  23. This does not simply profit an organization while the program is set up, yet long after because of its workers benefitting from a healthy way of life. A wellbeing way of life includes in excess of a man's physical state.Click Here

    ReplyDelete
  24. This continuum is a simple way of depicting the basic fact that earned health evolves largely due to our own efforts to improve and protect our well being; static health, on the other side is affected by what happens to you.
    best 10000 lux light box

    ReplyDelete
  25. Infrequently are common health supplements sold with tributes and previously/after photographs quickly accessible for your audit. However, you will discover them particularly on numerous online health locales.Turmericsupplementplus.com

    ReplyDelete
  26. This blog is a punchy piece of writing, as it has a strong effect.
    drug test cup

    ReplyDelete
  27. Meeting up is usually better since you pay for it upfront and you get the products right away. panic relief

    ReplyDelete
  28. It can likewise upgrade your vitality levels and invulnerability control if your body is deficient in it. this blog - click here

    ReplyDelete
  29. Regular health cure really holds a straightforward and viable answer for enhancing health. Regardless of how well individuals have assembled their expert work qualifications, those individuals still know almost no about how the human body functions.get information bodybuilding

    ReplyDelete
  30. Trust it or not, the most vital part of fitness is your eating regimen. It doesn't make a difference if your activity regimen is right on the money.fitness blog guest posthealth blog guest post

    ReplyDelete
  31. The blog is created in essential English with no longing towards composing.
    Healthier Land

    ReplyDelete
  32. Nonetheless, don't squander your cash on things you don't need. You can do exercise center workout at home. To carry on with a healthy life, practice is essential. It relies on your way of life.URL

    ReplyDelete
  33. Many vocation alternatives are accessible to understudies that look for instruction in general health. Authoritative obligations and systems for health related practices are considered inside a degree program. This can incorporate working with destitute and child care kids.Wellphora CBD

    ReplyDelete
  34. Mental health problems are not just a passing phase. Children are at greater risk for developing mental health problems when certain factors occur in their lives or environments. yoga program

    ReplyDelete
  35. Many children experience mental health problems that are real and painful, and they can be severe. hearburn no more review

    ReplyDelete
  36. Drink water, heaps of it. In spite of the fact that water doesn't have anything in it to enable you to get in shape, drinking a lot of it will enable your body to flush out poisons, hydrate your cells and advance your health. clenbuterol 40

    ReplyDelete
  37. LED televisions are usually chosen on the basis of the screen size. For a bigger room, you may opt for an LED TV with a screen size that is 32 Inch LED TVs or between 33 Inch - 42 Inch LED TVs, or 43 Inch - 54 Inch LED TVs. you can go to this link https://www.snapdeal.com/

    ReplyDelete
  38. Truly there is just a honestly excellent method to guarantee you'll obtain premium high-quality, correct function out of the translation agency which can be to make your final decision predicated on referrals. Are you able to know anybody having a prosperous long-term connection possessing a translation agency? Click right here https://rotend.shutterfly.com/39 to find out additional about translation services.

    ReplyDelete
  39. Our mission is to provide Maryland registered Medical Cannabis patients with access to the highest quality, most efficacious, and most carefully selected medications to relieve their ailments in a safe, welcoming, and comfortable environment. you can go to this link https://zhyathler.webnode.com/

    ReplyDelete
  40. It is about the Poker qq online sport, that this Website entertains you personally and you'll delight in lots this match whilst playing with it. For enjoying with this sport you have to stick to all of rules to be perfect gambler. Individuals who wish to know about agen poker Indonesia, they can visit to our website http://bitherach.pbworks.com/w/page/130549662/A%20Review%20Of%20Live%20poker%20qq%20online

    ReplyDelete
  41. A fantastic usb adapter ought to generally be able to manually deliver and protect documents towards your units that you choose to get extra routinely. This definitely is going to generally be referred to as a wonderful way of preserving time and electrical power ingestion in the have notebook. To find out more about usb adapter, stop by our https://www.bloglovin.com/@shebanther/best-usb-wifi-adapter-most-vital-tips web-site.

    ReplyDelete
  42. CBD Oil Wholesale endeavors to become the prevailing name in the sector of all-natural essential oils contributor. Click here https://ryoright.webnode.com/ to find out more about wholesale cbd oil.

    ReplyDelete


  43. You want to know way more about getting the webpage visitors focused prospects to each expose into revenue. Composing seo content material consists of a variety of aspects of creating. For way more details simply click here http://whaelmald.strikingly.com/

    ReplyDelete
  44. It is your main reason behind hiring a lawyer. Now you Are Interested in being supplied a written document with detailed advice concerning your house. Your following question ought to be the way you may get the report. One can visit the site http://bieghine.strikingly.com/ to get complete insights about Staten Island events today!

    ReplyDelete
  45. where people can find the products that they are searching for easy and make the decision of choosing the best product easy. We do reviews of products that are sold on Amazon.com and list them up in a top 10. you can go to this link http://moronim.strikingly.com/

    ReplyDelete
  46. many people upload their video’s to YouTube and waits patiently to get YouTube views and comments on their video. After refreshing their YouTube watch page a few hundred times, YouTube freezes their video counter at the dreaded 301+ mark. Does this sound familiar? you can go to this link http://sertver.strikingly.com/

    ReplyDelete