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. Dismiss Notice

Help with changing the Text field of a UI button C#

Discussion in 'Scripting' started by anathima, Dec 20, 2015.

  1. anathima

    anathima

    Joined:
    Dec 25, 2013
    Posts:
    4
    Buttons.png buttonmanager.png

    New to C#, and I am sure this is simple but i have been beating my head against it for a couple days.

    I need to change the text field on the "Number" child of "ButtonWater" via the script below. I am using Unity 4.6 Thanks in advance for any help.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4.  
    5. public class Script_CraftButMan : MonoBehaviour
    6. {
    7. //    public string ThisButton : UnityEngine.UI.Button;
    8.     public Transform craftingTable;
    9.     public string name;
    10.  
    11.     // Use this for initialization
    12.     void Start ()
    13.     {
    14.  
    15.     }
    16.    
    17.     // Update is called once per frame
    18.     void Update ()
    19.     {
    20.  
    21.     }
    22.  
    23.     public void AddToTable()
    24.     {
    25.         //Instantiates material into crafting table
    26.         GameObject test = Instantiate(Resources.Load("Prefabs/Prefab_" + name)) as GameObject;
    27.         test.transform.SetParent(craftingTable);
    28.  
    29.         //Here is where i am trying to access the text of the "Number" child.
    30.         this.GetComponentInChildren<GUIText>().text = "testing";
    31.     }
    32. }
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    GUIText is for legacy UI system

    you need:

    Code (csharp):
    1.  
    2. using UnityEngine.UI;
    3.  
    4. //...
    5. GetComponentInChildren<Text>().text = //...
    6.  
     
    minev likes this.
  3. anathima

    anathima

    Joined:
    Dec 25, 2013
    Posts:
    4
    Thanks that helped. But it is Changing the "Name" child and setting the "Number" child to Null. Any thoughts on how to specify the "Number" child as the one to change? Thanks again, I am getting closer.
     
  4. DuffyT

    DuffyT

    Joined:
    Dec 16, 2014
    Posts:
    37
    If you plan on changing that text alot, better cache it straight away. Make a public UI.Text field in your script. Drag the relevant Text-object you want to change into the field in the inspector and change the Text.text to whatever string you want as many times as you want in your script. It's also better performance-wise to not call getchild and getcomponent each time.