Null reference after adding Player health to UI

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() + " %";
        }

        
    }
}

I’m still new to this but I think this line of code above should be:

playerHealth = GameObject.FindWithTag(“Player”).GetComponent<BaseStats>( ).GetHealth();

Hope this works!

This null reference could be one of two things…
It could be the GetComponent<Text>().text, which would mean that the text component could not be found. Make sure there’s a Text component. The other possibility is that the Player doesn’t have a PlayerHealth, or does not have a tag of Player.

Try adding some debugs

private void Awake()
{
     playerHealth = GameObject.FindWithTag("Player").GetComponent<PlayerHealth>();
     Debug.Log($"Player Health located on {playerHealth}");
}

void Update()
{
    Text text = GetComponent<Text>();
     if(text!=null) text.text = playerHealth.GetPercentage()+"%";
     else Debug.Log("Unable to locate Text component");
}

Privacy & Terms