Ice*_*ain 0 c# unity-game-engine
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];
};
Run Code Online (Sandbox Code Playgroud)
小智 6
基本上,您需要制作变量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];
};
Run Code Online (Sandbox Code Playgroud)
所有这些背后的原因是一种叫做闭包的机制。您可以在此处找到有关此信息的更多信息:c#闭包
| 归档时间: |
|
| 查看次数: |
48 次 |
| 最近记录: |