Access Text inside Canvas by name

I have a Canvas with two Text elements inside, like this:


  1. FooText
  2. 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.

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

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.