- Home /
Change UI Text in new UI?
How do I change the text in the new UI system from a script? I am making a speedometer.
Answer by moriam · Mar 05, 2015 at 08:38 AM
you get the text component and change its text property.
MyTextObject.GetComponent<UnityEngine.UI.Text>().text = "Insert Text Here";
Like this?
#pragma strict
var $$anonymous$$yTextObject : GameObject;
function Start () {
}
function Update () {
var mph = GetComponent.<Rigidbody>().velocity.magnitude * 2.237;
$$anonymous$$yTextObject.GetComponent<UnityEngine.UI.Text>().text = mph;
}
its giving these errors: Assets/speed.js(9,46): BCE0043: Unexpected token: >. Assets/speed.js(9,49): BCE0044: expecting ), found '.'. and Assets/speed.js(9,48): BCE0043: Unexpected token: ).
It could be one of the following problems:
1) You wrote a dot after GetComponent when you retrieved the Rigidbody, remove it.
2) The code I wrote is in c#, if you are writing in javascript maybe it should be without the '<'
Try this:
var mph = GetComponent(Rigidbody).velocity.magnitude * 2.237;
$$anonymous$$yTextObject.GetComponent(UnityEngine.UI.Text).text = mph;
Ok, so it works, but the speed just continuously moves up.
Answer by Woj_Gabel_FertileSky · Mar 05, 2015 at 09:07 AM
For UI objects you need to use UnityEngine.UI.
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // <-- this guy right here
public class ChangeTextClass : MonoBehaviour
{
public Text textObject;
void Start()
{
textObject.text = "your new string!";
}
}
Your answer
Follow this Question
Related Questions
Cant drag InputField to property of script in Inspector 2 Answers
Navigate UI with gamepad 0 Answers
Hi, my drop down doesn't show the last option. 2 Answers
How can I make an on-screen speedometer? 2 Answers
Need script on speed 1 Answer