Home > database >  How do I get the text from a button after clicking it?
How do I get the text from a button after clicking it?

Time:12-16

I am trying to get the text of the button clicked to compare it to a string.

public void clicked()
    {
        Debug.Log("Timer done");
        secondsLeft = 0;
        timerOn = false;

        questionUI.SetActive(false);
        Paused = false;
        //turns off the question screen

        string answer = GetComponentInChildren<TMPro.TMP_Text>().ToString();
        if (questions[0] == answer)
        {
            PlayerQuests.points  = 1000;
        }
    }

This is the code I made which the button runs after being clicked. This should get the text inside the button which is a text mesh pro and compare it to a string in an array which is in index position 0.

CodePudding user response:

If you add using TMPro; at the top of your class, you should be able to get the text of the TextMeshProUGUI component by writing:

var answer = GetComponentInChildren<TextMeshProUGUI>().text;

CodePudding user response:

Would this work for your case?

  private void button5_Click(object sender, EventArgs e)
        {
            string s = (sender as System.Windows.Forms.Button).Text;
           label2.Text = s; //just an example of how s would be used
        }

  • Related