NewHacker
NewHacker

Reputation: 39

How to give information from a button?

I have four buttons like:

enter image description here

I also have a gameobject that attaches my script to it

Under the script I have one function, that should print the text of the button, when I use it in onClick() buttons.

Inspector

enter image description here

How to call one function on different buttons and print out the text of those buttons, that the user clicked?

Upvotes: 0

Views: 169

Answers (2)

Hardik Maru
Hardik Maru

Reputation: 691

Rather taking all the buttons in the list. Make a script Button.cs and give it to each UI buttons

In that script make one public method

public void OnButtonClickListener(int index) {
    // Do your code here for button click using its index
}

now you just have to assign callbacks of each UI buttons to this public method and pass the argument of button's index.

I hope this will help you...

Upvotes: 1

Programmer
Programmer

Reputation: 125255

Instead of passing the string to the callback function, it would make more sense to pass the Button instance itself. If you do this, you will be able to access more data from the Button if needed in the future.

public Button[] Btn;

void OnEnable()
{
    //Register Button Events
    for (int i = 0; i < Btn.Length; i++)
    {
        int btIndex = i;
        Btn[i].onClick.AddListener(() => buttonCallBack(Btn[btIndex]));
    }
}

private void buttonCallBack(Button buttonPressed)
{
    Debug.Log(buttonPressed.GetComponentInChildren<Text>().text);

    if (buttonPressed == Btn[0])
    {
        //Your code for button 1
    }

    if (buttonPressed == Btn[1])
    {
        //Your code for button 2
    }

    if (buttonPressed == Btn[2])
    {
        //Your code for button 3
    }

    if (buttonPressed == Btn[3])
    {
        //Your code for button 4
    }
}

void OnDisable()
{
    //Un-Register Button Events
    for (int i = 0; i < Btn.Length; i++)
    {
        Btn[i].onClick.RemoveAllListeners();
    }
}

If you still want to pass the Button text only:

public Button[] Btn;

void OnEnable()
{
    //Register Button Events
    for (int i = 0; i < Btn.Length; i++)
    {
        int btIndex = i;
        string btText = Btn[btIndex].GetComponentInChildren<Text>().text;
        Btn[i].onClick.AddListener(() => buttonCallBack(btText));
    }
}

private void buttonCallBack(string buttonText)
{
    Debug.Log(buttonText);
}

void OnDisable()
{
    //Un-Register Button Events
    for (int i = 0; i < Btn.Length; i++)
    {
        Btn[i].onClick.RemoveAllListeners();
    }
}

Remember to assign your Buttons to the Btn variable slot in the Editor or you will get the null exception error.

Upvotes: 1

Related Questions