- Home /
Health bar
I found this code for a health bar on here and i was wondering does anyone know how to change it so it decreases when he touches certain objects?! (just now it's like a count down/time thing) and i'm not sure how i'd change it.
I've just started using Unity and i'm hopeless at it so i'd appreciate it if anyone could help me out! Thanks! :)
Heres the code:
var barDisplay : float = 0;
var pos : Vector2 = new Vector2(20,40);
var size : Vector2 = new Vector2(60,20);
var progressBarEmpty : Texture2D;
var progressBarFull : Texture2D;
function OnGUI()
{
// draw the background:
GUI.BeginGroup (new Rect (pos.x, pos.y, size.x, size.y));
GUI.Box (Rect (0,0, size.x, size.y),progressBarEmpty);
// draw the filled-in part:
GUI.BeginGroup (new Rect (0, 0, size.x * barDisplay, size.y));
GUI.Box (Rect (0,0, size.x, size.y),progressBarFull);
GUI.EndGroup ();
GUI.EndGroup ();
}
function Update()
{
// for this example, the bar display is linked to the current time,
// however you would set this value based on your desired display
// eg, the loading progress, the player's health, or whatever.
barDisplay = Time.time * 0.05;
}
Gain some karma for knowing how to post correctly formatted script code.
Answer by Graham-Dunnett · Nov 29, 2012 at 11:38 AM
"Touches certain objects" in Unity means a collision has happened. So see:
http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnCollisionEnter.html
When you detect a collision, decrement the barDisplay variable. This should vary from 0 to 1 from looking at your posted script. So initialise it to 1 instead of zero.
Is that changing the 0 on the first line to 1? (sorry that probs sound stupid, i've just never really used unity and basically know nothing about editing and fixing code)
Your answer