Friday, July 20, 2012

How to make a health bar in Unity

Today I'm writing a short tutorial on how to create a simple health bar in unity... The code is actually pretty simple

Hopefully you already have a character script attached to a character... if not I may decide to do a simple one in a later tutorial.

in this character script we will add the OnGUI() function if we have not already done so. and a health float variable like so.

public var healthTex :Texture;
private var health:float = 1;  (note in this tutorial we will use 1 as full health 50 percent health would be .5)

OnGUI()
{
GUI.DrawTexture(Rect(Screen.width/4, 10,100*health,10), healthTex , ScaleMode.StretchToFill, true, 10.0f);
}


this will create a simple health bar that will scale based on how much health the character has.

if you want to create a back texture for an empty health bar for visual feedback you can also do this.

public var emptyHealth:Texture;

public var healthTex :Texture;
private var health:float = 1;  (note in this tutorial we will use 1 as full health 50 percent health would be .5)

OnGUI()
{
        GUI.DrawTexture(Rect(Screen.width/4, 10,100,10),  emptyHealth  , ScaleMode.StretchToFill, true, 10.0f);
GUI.DrawTexture(Rect(Screen.width/4, 10,100*health,10), healthTex , ScaleMode.StretchToFill, true, 10.0f);
}


the only difference is that we draw the empty health bar first and we do not times the width by health.

2 comments:

  1. I love you. I don't know if you're still getting notifications from your blogs, but this was extremely helpful. Thank you :)

    ReplyDelete