- Home /
Access Text inside Canvas by name
I have a Canvas with two Text elements inside, like this:
Canvas:
FooText
BarText
I would like to attach a C# Script to the Canvas and access both the Text objects from inside the script. Something similar to this:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class DisplayScore : MonoBehaviour {
Text fooText;
void Start () {
fooText = gameObject.GetComponent<Text>(); // ????
fooText.text="Change the text";
}
}
Basically, how would I access text element by its name? The question is trivial, but I am new to Unity and after digging tons of other answers need some help.
Answer by fafase · Mar 15, 2015 at 08:19 PM
Your objects are children of your canvas and the script is attached on the canvas so you can look in the Transform.
Transform child = transform.Find("ObjectName");
Text t = child.GetComponent<Text>();
// You know the rest
Answer by badatnames16 · Mar 15, 2015 at 08:01 PM
Just replace line 7 with
public GameObject fooText;
and in the inspector drag the text into the slot. Then put
Text footext = fooText.GetComponent<Text>();
fooText.text = "Change the text";
This worked for me.
Thank you. I know this works. But imagine that I have 10 elements inside. I was wondering if it is possible to get reference to the objects dynamically without having to make them public and drag-and-drop them manually.
You forgot to put the [SerializeField]
on the first variable, so it should actually be:
[SerializeField] public GameObject fooText;
without the [SerializeField]
you won't be able to see the variable in the inspector