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

Changing UI button text with C#

Discussion in 'UGUI & TextMesh Pro' started by Dawre, Sep 5, 2014.

  1. Dawre

    Dawre

    Joined:
    Sep 5, 2014
    Posts:
    6
    Hi,
    I'm trying to change UI text of an UI button by code. It should be like a countdown which enables the button after getting to zero:

    Code (CSharp):
    1. public float countdown = 5.0f;
    2. public Button button_play;
    3. //public ??? text;
    4.  
    5. void Update()
    6. {
    7. countdown -= Time.deltaTime;
    8. if (countdown <= 5.0f)
    9. {
    10. // button text: "Wait for 5"
    11. if ...
    12. if (countdown <= 0.0f)
    13. {
    14. // button text: "Next"
    15. Button_play.enabled=true;
    16. }
    17. }
    18. }
    Does anyone have an idea how to manipulate the UI text of an UI Button?
     
    dbrizov likes this.
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,738
    The class name you're looking for is "Text". You do need to add "using UnityEngine.UI;" to the top of your script to use it.
     
  3. ManAmazin

    ManAmazin

    Joined:
    Aug 7, 2013
    Posts:
    246
    You want to do it like this:

    Code (CSharp):
    1. button_play.text.text = "Wait for 5";
    as starManta stated make sure you add the "using UnityEngine.UI"
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,738
    Oh yeah, forgot buttons had that convenience property.
     
  5. Dawre

    Dawre

    Joined:
    Sep 5, 2014
    Posts:
    6
    I tried your suggestion, Computerkid23. Unfortunately this didn't work ... BUT this works:

    Code (CSharp):
    1.     using UnityEngine.UI;
    2.     public float countdown = 5.0f;
    3.     public Button button_play;
    4.     public Text btn_text;
    5.  
    6.     void Update()
    7.     {
    8.     countdown -= Time.deltaTime;
    9.     if (countdown <= 5.0f)
    10.     {
    11.     btn_text.text = "Wait for 5";
    12.     if ...
    13.     if (countdown <= 0.0f)
    14.     {
    15.     btn_text.text = "Next";
    16.     Button_play.enabled=true;
    17.     }
    18.     }
    19.     }
    20.  
    Thank you Manta and Kid! Problem solved :cool:
     
  6. ManAmazin

    ManAmazin

    Joined:
    Aug 7, 2013
    Posts:
    246
    No prob..just curious tho..because that little code should work when accessing the text of a button....unless you r using "btn_text" to replace the default test component of the button??

    Anyways glad you figured it out...
     
  7. mirobago

    mirobago

    Joined:
    Jun 27, 2017
    Posts:
    1
    Now we're sucking diesel. No one on internet during my 20min search could answear this question. Works like magic.