- Home /
Question by
MainframePT · Mar 16, 2014 at 07:39 PM ·
gamebarhealth
Health bar update
Hello,
I'm currently trying to add an Health bar to game and I'm having issues with updating its length. The bar itself is very basic, however whenever I alter the curHealth variable, the length of the Health bar isn't updated accordingly. For example, with a maxHealth of 100, the bar only updates when curHealth reaches values of for example, 50 or 35.
using UnityEngine;
using System.Collections;
public class HealthAmmoBars : MonoBehaviour {
GUIStyle shurStyle = new GUIStyle();
public Font myFont;
public int maxHealth = 100;
public int curHealth = 100;
public float healthBarLength;
private int numShur;
GUIStyle healthstyle = new GUIStyle();
Texture2D texture;
// Use this for initialization
void Start () {
shurStyle.font = myFont;
shurStyle.normal.textColor = Color.white;
healthBarLength = Screen.width / 4;
//texture = new Texture2D (128, 128);
//AssignTex(texture, red);
}
// Assign color to a texture
void AssignTex (Texture2D tex, Color col){
for (int y = 0; y < texture.height; ++y) {
for (int x = 0; x < texture.width; ++x) {
texture.SetPixel (x, y, col);
}
}
tex.Apply ();
}
void OnGUI() {
// Shuriken bar
string numShurProjStr = "Shurikens: " + numShur.ToString(); // Since its a static variable
GUI.Label(new Rect(10, 50, 500, 100), numShurProjStr , shurStyle);
// Health text
GUI.Label(new Rect(10, 22, 500, 100), "Health" , shurStyle);
// Health bar
GUI.Box (new Rect (50, 20, Screen.width / 4 / (maxHealth / curHealth), 20), curHealth + "/" + maxHealth);
//healthstyle.normal.background = texture;
//GUI.Box(new Rect(10,10,Screen.width / 2, 20),"" ,healthstyle);
}
public void UpdateHealth(int adj){
curHealth += adj;
// HP cannot below 0
if (curHealth < 0)
curHealth = 0;
// Cur HP cannot be higher than max HP
if (curHealth > maxHealth)
curHealth = maxHealth;
healthBarLength = (Screen.width / 4) * (curHealth / (float)maxHealth); // Full health length bar * (% of current health)
}
void Update(){
numShur = ShurikenProj.numShurikenProj;
//UpdateHealth (0);
}
}
Comment
Your answer
Follow this Question
Related Questions
Problem ProgressBar with health + Time the poison 1 Answer
Enemy healthbar script 2 Answers
How to add texture in onGUI() 0 Answers
Life Bar System Help 1 Answer
Health Help D: 2 Answers