- Home /
New UI: change text
Hey! I would like to change text on mouse pressed. I have a canvas and text parented to it. I've looked at API:
http://docs.unity3d.com/ScriptReference/Component.GetComponentsInChildren.html
and wrote a simmiliar code, but it doesn't work. In particular, in line: instruction.text = "this is text"; .text is highlighted red. Could you please help me? Thank you!
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class countscript : MonoBehaviour {
public Text[] instruction;
// Use this for initialization
void Start () {
instruction = GetComponentsInChildren<Text> ();
}
// Update is called once per frame
void Update () {
if (Input.GetButton ("Fire1")) {
instruction.text = "this is text";
}
}
}
Answer by _MGB_ · Feb 19, 2015 at 02:00 PM
Your 'instruction' var is an array. You probably want to use GetComponentInChildren instead of GetComponent*s*InChildren.
Answer by HarshadK · Feb 19, 2015 at 02:00 PM
Since you have declared instruction as:
public Text[] instruction;
your instruction is an array of Text elements.
So you can access elements inside an array using an index like:
instruction[0].text = "this is text";
to access the first element in the array.
Or using a for loop:
for (int i = 0; i < instructions.Length; i++)
{
instruction[i].text = "this is text";
}
Your answer
Follow this Question
Related Questions
How to use special symbols 1 Answer
Display Emojis using its HTML code in a text 1 Answer
Writing text to UI Text new line 1 Answer
,InputField backspace returns already send text 0 Answers
UI Text compression on android 1 Answer