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.