Currently I have a health bar script that will reduce the width of the texture based on the players current health percent ((CurrentHealth/MaxHealth)*100) the only problem is when the bar’s width is reduced the height will also decrease. Is there anyway to have this not happen? NOTE: the texture is a red health bar (being a rectangle)
var HealthForeGround : Texture2D;
//Player_Stats.PlayerHealthPercent always 0-100
function OnGUI(){
GUI.Label(Rect(200,50,2*Player_Stats.PlayerHealthPercent,100),HealthForeGround);
}
The way I would do this is to use a plane on which you apply your texture.
Then you can modify the localScale of the plane
Let’s say you have health from 0 to 100 (or the other way around)
int health,size;
Transform healthPlane;
void Start(){
healthPlane =GameObject.Find("PlaneForHealth").transform;
size = healthPlane.localScale.x;
health = 100;
}
void Update(){
if(health%20 == 0)ChangeColor();
}
public void SetSize(){
if(health == 80){
healthPlane.localScale = new Vector3(size * 0.8f,0f,0.03f);
}else if(health == 60){
healthPlane.localScale = new Vector3(size*0.6f,0f,0.03f);
}else if(health == 40){
healthPlane.localScale = new Vector3(size*0.4f,0f,0.03f);
}else if(health == 20){
healthPlane.localScale = new Vector3(size*0.2f,0f,0.03f);
}
}
So first you get the health plane object, you set its size as original size for full. The SetSize method will get called when the remainder of a division between the health and 20 is 0, that is when health is 80,60,40 and 20. Now if you want a constant decrease there it is:
int health, originalSize;
Transform healthPlane;
void Start(){
healthPlane =GameObject.Find("PlaneForHealth").transform;
originalSize = healthPlane.localScale.x;
health = 100;
}
void Update(){
healthPlane.localScale = new Vector3(size*health/100f,0f,0.03f);
}
Note that the 0.3f is just a value I used in my own code. Your value may and probably will be different.
EDIT:Advantage of using a plane only applies if you want to put the health bar above the character, if you need it in a corner then you do the same process with a GUITexture