HealthDisplay not updating

I’m tearing my hair out over this one! I’ve created a script called HealthDisplay.cs and added it to my HealthDisplay TextMeshPro object. This didn’t work (gave me a NullReferenceException) so I tried commenting it out and just printing the value (as in the below) which also didn’t work. I added the print in the Start() method as part of my debugging though, and that print seems to work fine - so something’s going wrong between the Start and the first Update? Any ideas?!

using UnityEngine;
using System;
using RPG.Attributes;

namespace RPG.Stats
{
    public class HealthDisplay : MonoBehaviour
    {
        Health health = null;

        void Start() {
            Health health = GameObject.FindWithTag("Player").GetComponent<Health>();
            print(String.Format("{0}%", health.GetPercentage()));
        }

        void Update() {
            print(String.Format("{0}%", health.GetPercentage()));
            //GetComponent<TextMeshProUGUI>().text = String.Format("{0}%", health.GetPercentage());

        }
    }
}

So what’s happending here is you’re accidentally creating a local Health health in Start.
Your declaration at the top is correct

Health health=null;

But in the Start Method, by prefacing health with the type Health, you’re masking the global health variable. Remove the Health so that it reads

health = GameObject.FindWithTag("Player").GetComponent<Health>();

and you shoudl be right as rain.

:man_facepalming: Thanks so much! It’s obvious when you know…

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms