UI按钮侦听器AddListener不在循环中工作 [英] UI button listener AddListener not working in a loop

查看:114
本文介绍了UI按钮侦听器AddListener不在循环中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对UI侦听器有问题.我尝试将点击侦听器分配给UI的for循环中的方法,但是每次我选择了最后一个选项时.

I've got problem with UI listener. I try to assign click listener to the method in for loop for UI, but every time I've got last option selected.

public Button[] options;

void Start () 
{
    for(int i = 0; i < options.Length; i++)
    {
        options[i].onClick.AddListener(()=> {OptionPressed(i);});
    }
}

private void OptionPressed(int i)
{
    print (i);
}

它总是打印3.我的问题是为什么?还有为什么3只有3个按钮,所以应该是2个?

It's always print 3. My question is why? and also why 3 while there is only 3 buttons, so it should be 2?

推荐答案

它打印3,因为您没有将i的值装箱,它的值在每次迭代时都会被重写.
要解决此问题,请尝试执行以下操作:

It prints 3 because you're not boxing the value of i, it's value is getting re-written each time it iterates.
To fix this try doing something like this :

for ( int i = 0; i < options.Length; ++i )
{
    int j = i;
    options[i].onClick.AddListener( () => { OptionPressed(j); } );
}

检查差异

这篇关于UI按钮侦听器AddListener不在循环中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆