1

In Unity I have the following code:

public Button[] SearchPlayers;

void Start() 
{
    for(int i = 0; i < 10; i++)
    {
       // SearchPlayers[i].onClick.AddListener(Click(i));//here error
       SearchPlayers[i].onClick.AddListener(Click);//not error
    }
}

void Click(int i)
{
   print(i+":button was clicked")
}

The problem is if you see my code there is an integer i. So that value gives an error.How can I solve this error?

Egyu Hook
  • 33
  • 1
  • 8
  • Can you specify your question? And give us more information about the context? What is SearchPlayers? – Rafiwui Oct 12 '17 at 09:39
  • SearchPlayers is button of Arrays – Egyu Hook Oct 12 '17 at 09:42
  • And what do you get as an output now? And what value do you want to add where? – Rafiwui Oct 12 '17 at 09:45
  • What problem??? https://stackoverflow.com/help/how-to-ask – Isma Oct 12 '17 at 09:49
  • The problem is if you see my code there is an integer i. So that value gives an error.How can I solve this error? – Egyu Hook Oct 12 '17 at 09:55
  • That is because you only add the function and not call it. The call happens when you press the button. And besides that I am pretty sure that a button cannot give a function a parameter when he calls it. – Rafiwui Oct 12 '17 at 10:00

1 Answers1

2

The problem is the context. Calling Click(i) returns void. AddListener does not accept void.

You could solve this problem by creating an appropriate context with which to provide the argument.

public Button[] SearchPlayers;

void Start() 
{
    for(int i = 0; i < 10; i++)
    {
        //Cache the value
        int index = i;

        SearchPlayers[i].onClick.AddListener(() => Click(index));
    }
}

void Click(int i)
{
   print(i+":button was clicked")
}
Joel
  • 1,580
  • 4
  • 20
  • 33