Hi all, I hope someone in the community can help me on this.
I’ve been using 4.6 for awhile now, mainly testing out the new UI system. However, I can’t seem to find any good documentation on how to change any of the components via script.
Does somebody know how I can change the Text component’s text? I’ve placed it inside the canvas and added a script that has a gameobject variable. Set that in the editor as the Text gameobject but can’t seem to see any relative information in VS2013’s intellisense.
Hi, First you would need to add this import:
using UnityEngine.UI;
Then, you can declare a Text field and later use getComponent to initialize it;
Text instruction;
void Start () {
instruction = GetComponent<Text>();
}
You would then be able to reference the instruction.text property and change it’s string to whatever you like, or any other properties. Of course, this would be a script attached to a gameobject with the text field.
I found this while taking a look at ShowSliderValue.cs which is included with the UI example project provided by Unity this week.
IMPORTANT: This is attached to the text component of my button in UI canvas
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class DisplayScore : MonoBehaviour {
Text txt;
private int currentscore=0;
// Use this for initialization
void Start () {
txt = gameObject.GetComponent<Text>();
txt.text="Score : " + currentscore;
}
// Update is called once per frame
void Update () {
txt.text="Score : " + currentscore;
currentscore = PlayerPrefs.GetInt("TOTALSCORE");
PlayerPrefs.SetInt("SHOWSTARTSCORE",currentscore);
}
}
I had this problem as well. First let me clarify, and I do apologize if it is not the same issue. I was, and I am assuming you are as well, trying to change the text on a button on my UI.
My solution was this, when the UI creates anything that has text it creates a Text type and attaches it to the canvas with your button. The way I was able to change this text was to use a public Text variable so that I can just drag and drop that very Text object into the script(I used UnityScript):
var buttonText: Text;
Then to change it in the script simply assign it a new value:
buttonText.text=“New Text!!!”;
It took me quite sometime to figure this out and when I did I felt like I should’ve already known this, lol.
How unity implements the UI is just like any other unity components.
You add GameObject and attach UI components to it. Once you have the game object you can get the UI components from it and change the properties.