This is my code for my Player. When I press U, I can see in the variable window that the player is taking damage, but the Health Bar doesn’t scale down.
Edit: I’ve found that health, when referenced by healthBar.SetHealth and healthBar.SetMaxHealth, is a null value? What am I missing here?
public class Player : MonoBehaviour
{
//variables
//verify that public floats can be updated through stat progression
public float maxHealth = 100;
public float maxStamina = 100;
public float maxMana = 100;
public float healthIncreaseRate, staminaIncreaseRate, manaIncreaseRate;
public float health, stamina, mana;
public HealthBar healthBar;
public StaminaBar staminaBar;
public ManaBar manaBar;
private bool dead = false;
//???
private bool fullHealth = true;
private bool fullStamina = true;
private bool fullMana = true;
// Start is called before the first frame update
public void Start()
{
health = maxHealth;
stamina = maxStamina;
mana = maxMana;
healthBar.SetMaxHealth(maxHealth);
staminaBar.SetMaxStamina(maxStamina);
manaBar.SetMaxMana(maxMana);
}
// Update is called once per frame
public void Update()
{
// if the player takes damage, health goes down
if (Input.GetKeyDown(KeyCode.U))
{
TakeDamage(20);
}
// Possible deaths
if (health <= 0)
Die();
//health, stamina, and mana increase over time
if (health < maxHealth)
{
health += healthIncreaseRate * Time.deltaTime;
}
if (stamina < maxStamina)
{
stamina += staminaIncreaseRate * Time.deltaTime;
}
if (mana < maxMana)
{
mana += manaIncreaseRate * Time.deltaTime;
}
}
public void Die()
{
print("You have died.");
dead = true;
}
public void TakeDamage(float damage)
{
health -= damage;
healthBar.SetHealth(health);
}
}
The HealthBar script is pretty basic:
public class HealthBar : MonoBehaviour {
public Slider sliderHealth;
public void SetMaxHealth(float health)
{
sliderHealth.maxValue = health;
sliderHealth.value = health;
}
public void SetHealth(float health)
{
sliderHealth.value = health;
}
}