I get a "NullReferenceException" when trying to change the text of a UI text box.
I'm simply trying to change the text of a UI text box, that is located in UICanvas>HintBody in my hierachy.
Below is my code:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class LoadingScreenLogic : MonoBehaviour {
Text HintBody;
void Start () {
HintBody = GetComponent<Text>();
HintBody.text = "It works!";
if ((PlayerPrefs.GetString("SceneToLoad") == "") || (PlayerPrefs.GetString("SceneToLoad") == "InitScreen")) {
Application.targetFrameRate = 120;
PlayerPrefs.SetString("SceneToLoad", "InitScreen");
}
}
void Update () {
Debug.Log(PlayerPrefs.GetString("SceneToLoad"));
if(Application.GetStreamProgressForLevel(PlayerPrefs.GetString("SceneToLoad")) ==1){
Application.LoadLevel(PlayerPrefs.GetString("SceneToLoad"));
}
}
}
However, whenever I try to change the text of the text box this way, this appears in the log and nothing happens: NullReferenceException: Object reference not set to an instance of an object LoadingScreenLogic.Start () (at Assets/Assets/Scripts/LoadingScreenLogic.cs:11)
I don't know where to go from here. I've tried making Text HintBody public (and private), but it doesn't work. I'm only really getting started with C#.
Answer by Dibbie · Nov 06, 2015 at 05:09 PM
@Sonickyle27 Hmm, says line 11, though your text is on line 10.
I imagine this script is actually on the object that already have the Text component on it? Because of how you are using "GetComponent", in this way, it only gets the component on the object the script is on, essentially, is the same as saying "this.gameObject.GetComponent" the way you are doing it.
If its on a separate object then the one that actually has the Text component on it, try using GameObject.Find. Or try creating a reference to your Text directly, by creating a variable, like "public Text theText", and attach it in your inspector.
$$anonymous$$oving the script to the same GameObject as the Text worked, thanks!
Your answer
Follow this Question
Related Questions
Certain scripts that are attached does not work after build, scene change and closing unity 0 Answers
How to send event to my canvas via script 0 Answers
Always pickup closest item? 0 Answers
Null Reference Exception only in second method 1 Answer
How Can i Get This bool to work? Just need someone willing to explain. 2 Answers