Guys, I am quite new to Unity so please explain to me as if I’m stupid.
I have tried previous answers on similar threads and they do not work for me. Maybe, I’m just not doing it right.
What I want is to be able to change the text on the canvas through script, but it doesn’t work.
What I got right now is this:
import UnityEngine.UI;
var textBox : GameObject;;
var messageText : GameObject;
var message : String;
var questOneCompleted : int = 0;
function Start () {
// textBox.GetComponent.<Text>().text = message;
}
function Update () {
if (questOneCompleted == 0) {
textBox.SetActive(true);
message = "Complete quest one";
textBox.GetComponent.<Text>().text = message;
}
}
To make it clear, the “Text” is child to the “textBox” in the hierarchy.
The set active command works perfectly alone though.
However, when I run the script, it posts an error: Object Reference not set to an instance of an object and points to this line:
textBox.GetComponent.().text = message;
Erm, so from what I understand, your hierarchy looks like this?:
textBox ← assuming this is probably a canvas?
Text ← has a Text component on it
If that’s how it’s laid out, the GetComponent call will return null. There is no Text component on the textBox object, it’s on the child.
Change line 3 of your code to this:
var textBox : Text;
The reason is you get the advantage of only being able to set the reference in the editor to the Text component you want. Unity is built off C# which is far less flexible than JS in terms of type safety. Get into this convention/habit and problems like these pop up way less, plus with this method you never even use a (relatively expensive) GetComponent call, and the code is easier to read:
function Update ()
{
if (questOneCompleted == 0)
{
textBox.gameObject.SetActive(true);
textBox.text = "Complete quest one.";
}
}
There’s also not really a need for the message or messageText variables, so I removed them from this example.
This haven’t worked for me =(
My hierarchy looks like this:
Canvas → textBox → Text
textBox is a grey box around the text to give it a “chat” look and be able to display both box and text just by ticking on the textBox
The code is connected to canvas
When I try to bind the Text to the message field in the inspector and then run the code, it gives me an error:
Object reference not set to an instance of an object
And it removes the text from the code inspector.
Edit 5 mins later:
When I linked a working (displayed on screen) text box to the script, it worked.
So this means I can’t edit the text that’s on the Text while it’s not on screen?
I will try to work my way around that and see how it goes.
Will post a reply with result about an hour. If you have additional suggestions please post.