How to have different arguments for button click when you have a lot of buttons?

I am working on a set of items inside a game each item has a card in a form of a button when the user clicks on it he goes to another UI where is asked whether he wants to equip or buy the item I have everything done except how can I know which item has been chosen when the user clicks on the button here is some of my code

foreach(Item item in items.items)
{
Button card = Instantiate(btn);

if (item.viewable == true)
{

foreach (Transform child in card.transform)
{
if (child.name == “Name”) child.GetComponent().text = item.name;
if (child.name == “Atk Dmg”) child.GetComponent().text = “” + item.stat1;
if (child.name == “Atk Rate”) child.GetComponent().text = “” + item.stat2;
if (child.name == “Number”) child.GetComponent().text = "Number: ";
if (child.name == “quantity”) child.GetComponent().text = “” + item.quantity;
if (child.name == “Image”) child.GetComponent().sprite = item.spirte;

}

}else
{
foreach (Transform child in card.transform)
{
if (child.name == “Name”) child.GetComponent().text = “UNKOWN”;
if (child.name == “Atk Dmg”) child.GetComponent().text = “???”;
if (child.name == “Atk Rate”) child.GetComponent().text = “???”;
if (child.name == “Number”) child.GetComponent().text = "Number: ";
if (child.name == “Image”) child.GetComponent().sprite = unknownSprite;

}
}
btn.onClick.AddListener(clickedOnCard); /* how to have different arguments */

card.transform.parent = grid.gameObject.transform;
}

On the 4th line from the bottom
How can I say clickedOnCard(number) so I can know which item the user clicked on?

if I remember rightly, all you need to do is put an argument in the method you want to call e.g. number in this case.

the argument must be a int(might be ok with a float) and I think you can only have a single argument.

1 Like

Thanks for the reply piggy, I can do that in unity, But I need to do it in script because my items will be a lot and dynamic

I would suggest to assign the callback function in code. There you can add a lamda expression and pass any arguments you want.
like this pseudo code:

// initialization code
foreach(UnityEngine.UI.Button btn in myButtons)
{
    btn.onClick.AddListener(new UnityEngine.Events.UnityAction(
        () => ObjectClicked(btn.gameObject)));
}

// ...
void ObjectClicked(GameObject clickedObject)
{
    // Do Something
}

Edit: I just reviewed your code again. Here is what you probably want:

    btn.onClick.AddListener(new UnityEngine.Events.UnityAction(
        () => clickedOnCard(item)));

// ...
void clickedOnCard(Item selectedItem)
{
    // Do Something
}
1 Like