Hi I am adding the UI damaged health percentage to the RPG game but the code is giving me a NullReferenceException: Object reference not set to an instance of an object
RPG.Displays.HealthDisplay.Update () (at Assets/Scripts/Displays/HealthDisplay.cs:26) not sure I understand why. Here is my code below
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPG.Stats;
namespace RPG.Player
{
public class PlayerHealth : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] float hitPoints = 100f;
PlayerHealth playerHealth;
private void Awake()
{
hitPoints = GetComponent<BaseStats>().GetHealth();
}
public float GetPercentage()
{
return 100 * (hitPoints / GetComponent<BaseStats>().GetHealth());
}
public void TakeDamge(float damage)
{
hitPoints = Mathf.Max(hitPoints -= damage, 0);
if (hitPoints <= 0)
{
Debug.Log("Your gone");
}
}
}
}
and this is my health display script
using UnityEngine;
using RPG.Player;
using UnityEngine.UI;
namespace RPG.Displays
{
public class HealthDisplay : MonoBehaviour
{
PlayerHealth playerHealth;
private void Awake()
{
playerHealth = GameObject.FindWithTag("Player").GetComponent<PlayerHealth>();
}
// Update is called once per frame
void Update()
{
GetComponent<Text>().text = playerHealth.GetPercentage() + " %";
}
}
}