I have spent several days on this issue and could really use some help!
In my game, I have a working enemy health system. It has been tested extensively and is working flawlessly. To go with the health system, I want to have a health bar above the enemy’s head. The health bar also works flawlessly so long as there is only one enemy.
The problem is that I have multiple prefabs that get spawned in that all need to behave individually. Each prefab’s health behave’s correctly and the health bar follows them correctly. What doesn’t work correctly is that whenever a prefab takes damage, it only changes the health bar of the first prefab that spawned. If that prefab is destroyed, it just switches the the oldest existing prefab.
I’ll post the health bar code below:
using UnityEngine;
using System.Collections;
public class HealthBarChanger : MonoBehaviour {
private static Vector3 size;
private static bool hasChanged = true;
public Sprite Health0;
public Sprite Health1;
public Sprite Health2;
public Sprite Health3;
public Sprite Health4;
public Sprite Health5;
public Sprite Health6;
public Sprite Health7;
public Sprite Health8;
public Sprite Health9;
public Sprite Health10;
private static float Health = 1, TotalHealth = 1;
private void FixedUpdate(){
if(hasChanged){
if((Health/TotalHealth) == 1){
GetComponent<SpriteRenderer>().color = new Vector4(0,0,0,0);
GetComponent<SpriteRenderer>().sprite = Health9;
}else{
GetComponent<SpriteRenderer>().color = new Vector4(1,1,1,1);
}
if(Health >= 0){
transform.localScale = size;
Debug.Log(size);
}else{
size.x = 0;
transform.localScale = size;
}
if((Health/TotalHealth) < .1){
GetComponent<SpriteRenderer>().sprite = Health0;
}
else if((Health/TotalHealth) < .2){
GetComponent<SpriteRenderer>().sprite = Health1;
}
else if((Health/TotalHealth) < .3){
GetComponent<SpriteRenderer>().sprite = Health2;
}
else if((Health/TotalHealth) < .4){
GetComponent<SpriteRenderer>().sprite = Health3;
}
else if((Health/TotalHealth) < .5){
GetComponent<SpriteRenderer>().sprite = Health4;
}
else if((Health/TotalHealth) < .6){
GetComponent<SpriteRenderer>().sprite = Health5;
}
else if((Health/TotalHealth) < .7){
GetComponent<SpriteRenderer>().sprite = Health6;
}
else if((Health/TotalHealth) < .8){
GetComponent<SpriteRenderer>().sprite = Health7;
}
else if((Health/TotalHealth) < .9){
GetComponent<SpriteRenderer>().sprite = Health8;
}
else{
GetComponent<SpriteRenderer>().sprite = Health9;
}
hasChanged = false;
}
}
public void ChangeBar(float health, float totalHealth){
Health = health;
TotalHealth = totalHealth;
size = transform.localScale;
size.x = health;
size.y = 8;
hasChanged = true;
}
}
And this is the code that invokes ChangeBar:
public bool DealDamage(float damageDealt){
health -= damageDealt;
healthBar.GetComponent<HealthBarChanger>().ChangeBar(health, 100f);
damageDealt = 0;
return (health <= 0);
}
Like I said, everything works except that it changes the wrong healthbar. Any help would be greatly appreciated!