- Home /
The question is answered, right answer was accepted
How to access Text(script) component in Unity?
I am trying to access the Text(script) component but I can't figure it out. I've tried something like this but no dice:
numericalScore.GetComponent<Text>().text = "Score : " + scoreManager.score;
Here's a pic of the Text component I'm talking about:
using unityEngine.Ui;
Text txt;
void update(){
txt.text= (¨score¨+ scoremanager.Score);
}
Answer by Priapist · Mar 06, 2016 at 11:23 AM
I know this is a couple of years old, but it comes up in Google, so here's a simple, plain text response:
The Text class is in the UnityEngine.UI Namespace. So you can either go with:
numericalScore.GetComponent<UnityEngine.UI.Text>().text = "Score : " + scoreManager.score;
Or you can add the UnityEngine.UI namespace to your using block at the very top of your script:
using UnityEngine.UI;
Answer by danidu93 · Mar 05, 2016 at 01:00 AM
Lets imagine you have a Text (Game object ) which is called MainText To edit this text from your script you have to do this:
Lets image you have a Text (Game object ) which is called MainText
To edit this text from your script you have to do this:
public class EditText()
{
Text myText;
public void blablabla()
// not that your function must be public if you want to atach the script to your text
{
myText=GameObject.Find("MainText").GetComponent<Text>();
// here the variable myText reference to the game Object MainText
myText.text="Hello";
// or you can also do this
string example="Hello2";
myText.text=example // this will show you Hello2
// there are also other function for example to change color
myText.color=Color.red // your text color will be red
} // end of the funtion
} // end of the class
Once you do this save the script then click "Add Component" then "Scripts" then chose the script you have createdI hope this is gonna help you ,sorry for my bad english
Answer by shadowsaint669 · Mar 04, 2016 at 01:25 PM
If you are not you need to use includes UnityEngine.UI;
Answer by Poon-Moon · May 22, 2017 at 02:49 PM
To access Text as a component, you'll need UnityEngine.UI
using UnityEngine.UI;
Which then allows you to grab the Text component from the game object in question:-
numericalScore.GetComponent<Text>().text = myScore;
myScore will need a ToString() if it is not a String.
Follow this Question
Related Questions
GUI Problem 1 Answer
Unity UI never stays in place 1 Answer
Problem Displaying Score on GUI text 0 Answers
Get GUI Text Object to appear in the top left corner of the screen. 3 Answers
Guitext hides PHP text on iphone 0 Answers