I have tried everything I know to do, but I cannot get my label to change text through code. Yes, I have looked it up, but nothing seems to work!
Assuming you have a scene that contains a Canvas and a child object containing a UI.Text component, add the following example script to your text object.
using UnityEngine;
using UnityEngine.UI; // The namespace for the UI stuff.
using System.Collections;
public class SandBox_10 : MonoBehaviour {
private Text m_TextComponent;
void Awake()
{
// Get a reference to the text component
m_TextComponent = GetComponent<Text>();
m_TextComponent.text = "This is the new text.";
}
}
Here is an image of the scene hierarchy
Thanks for the reply, but is there anyway you could write this for js?
I am bumping this as I still can not get it to work in javascript…
I have the exact same problem and I must have read/watched 100 you tube videos… Its not working for me on a Mac (5.3.4f1)
I am using C#… still not working…
Take a look at the example I posted above which works. You have to make sure you add the “using” statement to include the UnityEngine.UI namespace.
SOLVED !!!.
use the type UnityEngine.UI.Text as below where appropriate.
public UnityEngine.UI.Text testchange;
and GetComponent<UnityEngine.UI.Text>();
NOT
public Text testchange;
Get Component();
I found it in the Debugger. The variable type listed as Text(UnitEngine.UI.Text);
Sorry I cant write it in Java for you…
As per the example I provided and my last post, you need to either reference the namespace of the text class or include it using.
using UnityEngine.UI; // The namespace for the UI stuff.
I am not using it because I learned on Javascript and I haven’t had time to switch over, but I do plan on learning it one day.
Thank you all for the help! I looked at it again today and got it working! Here is the code if anyone else is having this problem:
#pragma strict
var IsRock : boolean;
var RockAmount : int;
function Start () {
if(IsRock == true){
var text : UnityEngine.UI.Text;
text = gameObject.GetComponent(UnityEngine.UI.Text);
text.text = "Rock: "+RockAmount;
}
}
Thanks for the post! It makes things work.