- Home /
Basic Health Bar Display Problem
I have a simple health bar script attached to an enemy. When I press a key the enemy health and health bar are supposed to reduce in size. To a certain extent this happens but not exactly as I would like.
When I press the key the enemy's health decreases as expected. But the size of the bar only decreases when the enemies health gets below half!
I have some heavily commeneted code that does this.
First the enemyHealth script
var currHealth = 100; //currentHealth var maxHealth = 100; //maxHealth var healthBarLength; //length of healthbar
function Start() { healthBarLength = ((Screen.width/2)/(maxHealth / currHealth));//set default length }
function Update () {
}
function OnGUI() { GUI.Box(Rect(10,40,healthBarLength,20), currHealth + "/" + maxHealth);//draw health bar
}
//method for adjusting the health bar function AdjustHealthBar() {
if ((currHealth > 0) && (currHealth <= maxHealth)){ healthBarLength = ((Screen.width/2)/(maxHealth / currHealth)); } else { healthBarLength = 0; } }
//accessor for adjusting health function AdjustCurrentHealth(adj) { currHealth += adj; AdjustHealthBar(); }
Second the small piece of code which reduces the health (attacks):
var target : GameObject; //the player's target
function Update () { if (Input.GetKeyUp(KeyCode.F)) { Attack(); } }
function Attack() { var eh = target.GetComponent("EnemyHealth"); //var for enemy health script
eh.AdjustCurrentHealth(-10); //take 10 off enemy health }
I cannot figure out why this does not work and why I get the seemingly random result of the health bar staying the same length until health gets to 50/100.
Answer by GesterX · Aug 28, 2010 at 05:41 PM
Managed to solve this myself.
I combined both functions for adjusting the health and bar into one and changed the health bar calculation to the following:
function AdjustCurrentHealth(adj) { currHealth += adj; if ((currHealth > 0) && (currHealth <= maxHealth)){
healthBarLength = ((Screen.width/2)*(currHealth / maxHealth)); } else { healthBarLength = 0; } }
The key part being:
healthBarLength = ((Screen.width/2)*(currHealth / maxHealth));
Ugh, you know, I think I noticed that you were multiplying the Screen width ins$$anonymous$$d of dividing at first. And then when I came back to it, I started dividing, and completely blocked out the multiplication symbol. -.-
Your answer
![](https://koobas.hobune.stream/wayback/20220613072241im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Health Bar to Render On Top 2 Answers
Healthbar Energy Bar and MiniMaps? 0 Answers
need help with GUI healthbar 1 Answer
How do i add a healthbar/actionbar gui 4 Answers
Player grounder cheacker 1 Answer