Hello Everyone,
I'm new to Unity but I'm getting along so far from the great tutorials and questions that have already been answered. I have created the script below to display the health of enemy or companion characters but which character is dependent on a Raycast from the camera (in the direction of the player) and is not initialised in void Start(). I get the "NullReferenceException" error from line 40 but it is still playable and works as intended. I just think there must be a way to code this better to avoid the error.
CharacterHealthManager playerHealth;
CharacterHealthManager selectedHealth;
CanvasGroup cg;
public Slider healthBar;
public Slider selectedHealthBar;
public Image selectedHealthBarFill;
public Text hpText;
public Text selectedHPText;
public Text objName;
// Use this for initialization
void Start () {
playerHealth = GameObject.FindGameObjectWithTag("Player").GetComponent();
cg = GetComponentInChildren();
}
// Update is called once per frame
void Update() {
healthBar.maxValue = playerHealth.characterMaxHealth;
healthBar.value = playerHealth.characterCurrentHealth;
hpText.text = "HP: " + playerHealth.characterCurrentHealth + "/" + playerHealth.characterMaxHealth;
DisplaySelectedHealth();
}
void DisplaySelectedHealth()
{
if (GameObject.FindGameObjectWithTag("MainCamera").GetComponent().selectedObject.GetComponent() != null)
{
cg.alpha = 1;
selectedHealth = GameObject.FindGameObjectWithTag("MainCamera").GetComponent().selectedObject.GetComponent();
if (selectedHealth.CompareTag("Ally"))
{
selectedHealthBarFill.color = Color.magenta;
//TODO add Color.Lerp for smooth color transition.
}
else if (selectedHealth.CompareTag("Enemy"))
{
selectedHealthBarFill.color = Color.black;
}
objName.text = ("" + selectedHealth.name);
selectedHealthBar.maxValue = selectedHealth.characterMaxHealth;
selectedHealthBar.value = selectedHealth.characterCurrentHealth;
selectedHPText.text = "HP: " + selectedHealth.characterCurrentHealth + "/" + selectedHealth.characterMaxHealth;
}
else
{
cg.alpha = 0;
}
}
}
↧