Changing Text Via Script C# ?

Hello ive recenely Created a simple Health script & now i simply want to display the value of my hp but before i have evan got close to doing this i keep getting an error “Object Refrence not set to an instance of an object” evan tho i am setting the Refrence i still get this error … when the game is played the Text removes itself from the refrence on the script component … could anyone tell me why :S ? Thanks …

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class _Health : MonoBehaviour {
   
    public Slider HealthSlider;
    public Text HpText;

    public float Health;
    public float Max_Health = 250;
    public float Mana;
    public float Max_Mana;
   
    private float percentOfHp;
    private float hpBarLength;
   
    // Use this for initialization
    void Start ()
    {
        HpText = GetComponent<Text>();
        Health = Max_Health;
       
    }
   
    // Update is called once per frame
    void Update ()
    {
        Hp ();
        HpText.text = "HP";
    }
   
    public void Hp()
    {

        percentOfHp = Health/Max_Health;
        HealthSlider.value = percentOfHp/1.0f;
       
        if (Health > Max_Health)
            Health = Max_Health;
       
        if(Input.GetKeyDown("f"))
            Health -= 10.0f;
       
        if (Health <= 0){
            Debug.Log ("Oh Dear... You Are Dead");
            Health = 0;
           
        }
       
        if(Health <= 0) {
            HealthSlider.value = Health; //*10f;
        }
       
    }
}
HpText = GetComponent<Text>();

This is going to reach out and try to find a component on the CURRENT GameObject called “Text”. If no such component exists, then it’ll set it to null. If you’re setting the reference in the Inspector, then delete this line entirely.

1 Like

Ohhh i see wow -.- … Thanks Heaps its Working now :slight_smile: