Search code examples
unity-game-enginechildren

How to get text from specific child(button) when there are many


I have 6 buttons. Each has a different text on it. Pushing any button calls the one same method which changes the text and changes button positions between them. I can't figure out how to get the text from a specific button when it pushed. I can only return either random button text or all of them. Somewhat like this:

    public void ReadFromButton()
{
    Button button;
    button = GetComponent<Button>();
    var koba = button.GetComponentInChildren<Text>().text;
    Debug.Log(koba);



}

So I need any advice. Thanks.

buttons


Solution

  • You can add an int to your button click function like ReadFromButton(int i) and then in unity give your buttons numbers in onclickevent, according to your public Text[] buttontexts

    Like:

    public Text[] buttontexts;  
    public void ReadFromButton(int i)
    {
        var koba = buttontexts[i].text;
        Debug.Log(koba);
    }
    

    But i believe there is more ways to do that.