1
\$\begingroup\$

I have a prefabbed button (UI.Button) which I'm instantiating ten times:

public void LayoutButtons() {

    GameObject newCanvas = Instantiate (canvas) as GameObject;

    for (int i = 0; i < 10; i++) {
        buttons[i] = Instantiate(button, new Vector2((i * 100.0F)-500, -100), Quaternion.identity) as GameObject;
        buttons[i].transform.SetParent(newCanvas.transform, false);
        buttons[i].GetComponentInChildren<Text>().text = "Button " + i;
    }
}

However, I'm now stuck when trying to figure out which button was clicked. The Unity onClick seems to only allow zero or one parameters. I've tried using public void onClick(Button button) with button.getComponentInChildren<Text>().text but I get ArgumentException: failed to convert parameters

All I want to do is print out the clicked button's text. How can I do this?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Instead of using the built-in onClick in the Editor, make your own and add the listener yourself.

public void PrintText(string buttonText) {
    Debug.Log("Clicked " + buttonText);
}

Add a listener in to your LayoutButtons function (you don't need to keep track of the buttons using the array so just use tmp or something):

tmp.GetComponentInChildren<Button>().onClick.AddListener( () => { PrintText(tmp.GetComponentInChildren<Text>().text); });
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .