Having trouble with changing the text of a UI element. The script works and changes the text but i get this error?
"nullreferenceexception object reference not set to an instance of an object " It says its this line of code but not sure what im doing wrong here?
AuthText = GetComponent<Text>();
Full Code
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Logic : MonoBehaviour {
public Text AuthText;
public void Start ()
{
AuthText = GetComponent<Text>();
}
public void Update()
{
AuthText.text = "It worked";
}
}
That’s weird. If the GetComponent is returning a null it should only give the null reference exception in the Update when you try to do the assignment to .text. If that were the case, you would get the null reference exception error in the console over and over and over as it fires in each Update.
But if the error is actually happening in Update then the problem is likely because the Text component you’re trying to access is on a different gameobject than your script. If it’s on a child or parent gameobject you may have to use GetComponentInChildren or GetComponentInParent or something similar. Although you could just also place the appropriate Text component in the public variable using the Inspector.
Is this script on the same gameObject that has the text component? If it’s not you need to first FIND that object. In my tutorial series, I cover a get component video you can check out links in sig
if the above script is attached to the canvas the text object will be a child. There is FindComponentInChildren() function, but I think that just returns the first one it finds in the hierarchy so if you have several you’ll need to use tags, or rename the text child object and use find.
My issue was i was adding the script to the text object it self. When i made empty and instead attached it to that it solve the error.