如何在按钮点击功能上增加价值?

时间:2017-10-12 09:34:32

标签: unity3d

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 。因此该值会产生错误。如何解决此错误?

1 个答案:

答案 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")
}