Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How do I change button text content?

Discussion in 'UGUI & TextMesh Pro' started by epicsun, Apr 29, 2015.

  1. epicsun

    epicsun

    Joined:
    Apr 29, 2015
    Posts:
    5
    Code (CSharp):
    1.         GameObject canvas = GameObject.Find("Canvas");
    2.         Button[] btn = canvas.GetComponentsInChildren<Button>();
    3.  
    4.         foreach (Button b in btn)
    5.         {
    6.             Text txt = b.GetComponent<Text>();
    7.             if (txt)
    8.             {
    9.                 txt.text = "opponent round";
    10.             }
    11.         }
    it does not work !!! please help me~~~
     
  2. epicsun

    epicsun

    Joined:
    Apr 29, 2015
    Posts:
    5

    i want change button's text
     
  3. fffMalzbier

    fffMalzbier

    Joined:
    Jun 14, 2011
    Posts:
    3,276
    The problem is that the text is not on the button itself but it a child object of the button.
    That way your "b.GetComponent<Text>();" will get no text at all.
    Change line 6 to
    Code (CSharp):
    1. Text txt = b.GetComponentInChildren<Text>();
    That way you get the text component on the child.
     
    MD_Reptile and SimonDarksideJ like this.
  4. epicsun

    epicsun

    Joined:
    Apr 29, 2015
    Posts:
    5

    Thank you very much ,you help me a lot~~~