Change text of Button in Unity

15,626
   public Button b1;
public TextMeshProUGUI b1text;


void Start()
{
    b1text = b1.GetComponentInChildren<TextMeshProUGUI>();
    btnValue();
}

public void btnValue()
{
    b1text.text = "sdfa";
}

or you could just create a

public TextMeshProUGUI txt;

drag the textmeshpro text in the inspector and change the text.

    txt.text = "sdfa";
Share:
15,626
Ak Pasaf
Author by

Ak Pasaf

Updated on June 08, 2022

Comments

  • Ak Pasaf
    Ak Pasaf almost 2 years

    I am trying to Change the text of Button when opening the scene in Unity. I tried different methods to change the text of Button.

    Here is my code:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using TMPro;
    
    public class script : MonoBehaviour {
    
        public Button b1;
        public TMP_Text b1text;
    
    
        void Start()
        {
            GameObject b1object = (GameObject)Instantiate(b1);
            b1text = b1object.GetComponentInChildren<TMP_Text>(true);
            btnValue();
        }
    
        public void btnValue()
        {
            b1text.text = "sdfa";
        }
    
    }
    
  • Ak Pasaf
    Ak Pasaf over 5 years
    what did you use for b1object?
  • Ak Pasaf
    Ak Pasaf over 5 years
    TextMeshProUGUI class reference not working anymore.forum.unity.com/threads/…
  • joel64
    joel64 over 5 years
    did you put the namespace . using TMPro; ? You are using textmeshPro right ?
  • Ak Pasaf
    Ak Pasaf over 5 years
    Yes, I put the namespace and am using Textmeshpro for android.
  • Ak Pasaf
    Ak Pasaf over 5 years
    I want to change the text of the button.
  • Ak Pasaf
    Ak Pasaf over 5 years
    I changed my code to:using UnityEngine; using UnityEngine.UI; using TMPro; public class script : MonoBehaviour { public Button b1; public TextMeshProUGUI b1text; void Start() { GameObject b1object = Instantiate(b1.gameObject); b1text = b1object.GetComponentInChildren<TextMeshProUGUI>(); btnValue(); } public void btnValue() { b1text.text = "sdfa"; } }
  • Ak Pasaf
    Ak Pasaf over 5 years