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 hereYou also need to make a GUI.skin, which you can do by going to your project overview, clicking create and at the bottom there should be the option for GUI.skin.
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),"");
GUI.skin = customGUISkin;
GUI.Box(Rect(10, 10, (200 * (playerHealth / playerHealthMAX)), 20),""); // health bar is 200 wide at maximum health
GUI.skin = null; // put the GUI.skin back to default
}
}
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 GUI.skin you made into the slot for custom GUISkin.
Any problems, leave a comment! :)
No comments:
Post a Comment