Thursday, August 23, 2012

Unity3D : Making a Health Bar

Jeez, I was around when game magazines made jokes about the idea of a 'Health Bar' being some kind of spa in Europe or something. It was all new fangled back then...

Anyway, I had a heck of a time recently looking up a way of making a health bar in unity. I have found a way - not quite perfect, as the bar doesn't shrink perfectly when at low health. But looks nice enough and if the characters that low, they probably will die before they notice the problem. Maybe at some point in future I'll suddenly discover a better way to code it. Anyway, so this is the basic code:

var playerHealth : float = 100.00; // use your health var here
var playerHealthMAX : float = 100.00; // use your MAXIMUM health var here (to calculate a percentage from)
private var playerHealthBar : float; // just a var that holds playerHealth as a percentage
var customGUISkin: GUISkin;

function OnGUI ()
    playerHealthBar = playerHealth / playerHealthMAX;   // playerHealth as a percentage
    if (playerHealth > 0)
       GUI.Box(Rect(10, 10, 200, 20),""); = customGUISkin;
       GUI.Box(Rect(10, 10, (200 * (playerHealth / playerHealthMAX)), 20),""); // health bar is 200 wide at maximum health = null; // put the back to default
 You also need to make a, which you can do by going to your project overview, clicking create and at the bottom there should be the option for

Go into it and open up the box options. Near the top you'll find 'normal'. Open that up and you'll find a background option. It's here you can drag a graphic in - in this case, probably something 200 pixels wide, 20 tall.

Then make sure you add this script to an object (like your main camera), then in the inspector make sure to drag the you made into the slot for custom GUISkin.

Any problems, leave a comment! :)

No comments:

Post a Comment