在 Unity 中,我有以下代码:
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")
}
问题是,如果您看到我的代码有一个整数 i
。因此该值会产生错误。如何解决此错误?
答案 0 :(得分:1)
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")
}