I Have a Health bar but every time i get some damage, the health bar regenarates automaticlly.

function OnGUI() {
GUI.backgroundColor = Color.green;
GUI.Button(Rect(10,640,510,20),“Health”);

}

Heres the damage script

var damage = 2;
// instant kill
function OnCollosionEnter ( collisionInfo ) {
	collisionInfo.other.SendMessage("ApplyDamage", damage,
	SendMessageOptions.DontRequireReceiver );
	
}

Looks like it never changes :P

3 Answers

3

function OnGUI() {
GUI.backgroundColor = Color.green;
GUI.Button(Rect(10 * yourhealthvariablehere,640,510,20),“Health”);
}

Wouldnt that just move the healthbar? I think you should put variable in Rect(99,99,healthBarVariable, 20);

oh yes sorry

Well this is from the Docs

MonoBehaviour.OnGUI

OnGUI is called for rendering and handling GUI events.

This means that your OnGUI implementation might be called several times per frame (one call per event). For more information on GUI events see the Event reference. If the MonoBehaviour’s enabled property is set to false, OnGUI() will not be called.

You could try a conditional statement to check a variable for the amount of HP left. If it’s 0 then draw a empty rect.

I would advise using a GuiTexture instead of the unity gui system for healthbars. Just use a similar rectangle creation to show it on screen. You will have to use Camera functions to get screen points to draw (unless you want a 3d effect where health bar can be seen from the side). I used the GuiTexture method and it works fine. You can find a bunch of youtube videos for healthbars and such for unity.

It could be because its a button not a Box