Reputation: 113
I have an array of buttons used to select items from an array. What I'm trying to do is use one function to handle this, like the code below, instead of writing a lot of functions just doing a small job.
However, it seems all of those buttons are set to the last i
and it gives an "array out of bound" exception every time I click on the button.
Is there any better way to do this?
I considered to search for the index of clicked button, but that feels weird to me and could be slow.
public Button[] MPS;
for(int i = 0; i < gm.MP.Length; i++)
{
MPS[i].onClick.AddListener(() => MPButtonHandle(i));
}
void MPButtonHandle(int i)
{
MP = gm.MP[i];
};
Upvotes: 0
Views: 52
Reputation: 134
Basically you need to make a local copy of variable i:
public Button[] MPS;
for(int i = 0; i < gm.MP.Length; i++)
{
int j = i;
MPS[i].onClick.AddListener(() => MPButtonHandle(j));
}
void MPButtonHandle(int i)
{
MP = gm.MP[i];
};
The reason behind all of this is a mechanizm called closures. You can find more info about this here:c# closures
Upvotes: 6