I am trying to integrate a health bar system into my project. I have already got a script on my enemy that causes damage to my player on collision, and player health goes down correctly (which I can see via Debug.Log). However, for some unknown reason the Health Bar transforms straight to 0, and the text shows 0% after just one hit from the enemy. Any help would be much appreciated.
Code for HealthBar:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerUI : MonoBehaviour {
public static int playerCurrentHealth;
public Text gameOverText;
public Image currentHealth; //Healthbar
public Text healthPercentText; //Healthbar
void Awake ()
{
playerCurrentHealth = gameObject.GetComponent<PlayerStats> ().playerMaxHealth;
}
private void Start()
{
UpdateHealthBar ();
}
public void UpdateHealthBar()
{
int healthPercent = playerCurrentHealth / (gameObject.GetComponent<PlayerStats> ().playerMaxHealth);
currentHealth.rectTransform.localScale = new Vector3 (healthPercent, 1, 1); //Needs fixing, health bar doesn't change!
healthPercentText.text = (healthPercent * 100).ToString () + '%'; //Displays 100% but doesn't update!
}
}
Code for Enemy Damage:
void OnCollisionStay(Collision attack) //Attacking the player
{
if (attack.gameObject.tag == "Player" && PlayerUI.playerCurrentHealth > 0 && Time.time > enemyAttackTimer)
{
PlayerUI.playerCurrentHealth -= (gameObject.GetComponent<EnemyStats>().enemyDamage - GameObject.Find ("Player").GetComponent<PlayerStats> ().playerArmorRating);
GameObject.Find ("Player").GetComponent<PlayerUI> ().UpdateHealthBar (); //This line is to call health bar function UpdateHealthBar
Debug.Log ("You have been hit! Current Health: " + PlayerUI.playerCurrentHealth);
enemyAttackTimer = Time.time + gameObject.GetComponent<EnemyStats> ().enemyAttackDelay;
}
}
EDIT: I had NullReferenceExceptions appearing on play, but had 2 of the same script attached to the player and one missing object references. Problem of health dropping straight to zero still persists.