Hi all, I'm working on a health GUI bar & I need a little help fixing an object error that I'm getting. The error: NullReferenceException: Object reference not set to an instance of an object GuiTest.Update () (at Assets/scripts/GuiTest.cs:51) The code: Code (CSharp): /// <summary> /// GUI test. /// attach this to corresponding UI objects /// </summary> using UnityEngine; using UnityEngine.UI; using System.Collections; public class GuiTest : MonoBehaviour { private int startHealth = 100; public Text txtHealthString; //text field display public GameObject guiHealthBarObj; //health bar display public Object guiHealthBarImg; //health bar image private int testValue = 10; private int updatedValue = 0; //private int newValue = 0; // Use this for initialization void Awake () { //updatedValue.ToString(); txtHealthString.text = "Start Health: " + startHealth; txtHealthString = GetComponent<Text>(); print("starting: " + startHealth); print("updated value: " + updatedValue); } void Update () { //txtHealthString.text = startHealth.ToString (); //print (txtHealthString); //updatedValue.ToString(); //startHealth.ToString(); //txtHealthString = GetComponent<Text>(); if (Input.GetKeyUp ("up")) { AddInt (); txtHealthString.text = updatedValue.ToString (); print("updated value: " +updatedValue); } if (Input.GetKeyUp ("down")) { SubInt (); txtHealthString.text = updatedValue.ToString (); //else{return;} print("updated value: " +updatedValue); } } void AddInt() { updatedValue = startHealth + testValue; txtHealthString = GetComponent<Text>(); //print(updatedValue); } void SubInt() { updatedValue = startHealth - testValue; txtHealthString = GetComponent<Text>(); //print(updatedValue); } /* void UpdateGraphic() { if (updatedValue == 75) { //guiTexture.texture = ""; } }*/ // Update is called once per frame } Please help me figure out what I'm doing wrong. Thank you in advance
Question: If txtHealthString is assigned in the inspector, why do you keep on GetComponent'ing for it? Maybe the GetComponent is making it null during runtime Question 2: More than 1 instance of the script in the scene? eg on an object where there is no text component?
thanks hpjohn, got rid of the GetComponent & fixed the error...I suppose I was confused with implementing the code