foreach 循环给 Unity 中的按钮赋值的问题 [英] Problem with foreach loop giving values to a button in Unity

查看:40
本文介绍了foreach 循环给 Unity 中的按钮赋值的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 Unity 中为我的游戏制作类似于 Candy Crush 的地图,我试图将所有按钮收集到一个数组中,然后设置其 onclick 属性,以便当我点击它们时,我会到达关卡我想要.我正在使用 Foreach 循环来实现它.

问题是在每个按钮上,我都可以加载相同的场景.它确实列出了我从 1 到 N 的级别,但 onclick 似乎无法正常工作!我试过用 for 循环代替 foreach 但它也不起作用.

int i = 0;foreach(游戏对象级别在级别){level.GetComponent

解决方案

您已经在循环变量上创建了一个闭包.一个常见的陷阱,当然.StackOverflow 上已经存在对此类问题的适当解释和补救措施.

当您使用符号 i 时,它本质上是对存在于循环之外的唯一一个 i 的引用.它的值,当任何侦听器被调用时,将是它在循环结束时的值,在您的情况下,这将是您拥有的 levels 的数量.>

为避免这种情况,您需要使用i,而不是对变量的引用.您可以通过创建一个新变量来实现这一点,该变量的作用域对于循环的一次迭代是唯一的,并传入该新变量的值.基本上,icopy 就是您所需要的.

必要改变的本质是:

int i = 0;foreach(游戏对象级别在级别){int copy_of_i = i;level.GetComponent

I'm trying to do a Candy Crush-like map for my game in Unity, I'm trying to gather all the buttons in an array and then set its onclick property so when I click on them I get to the level I want. I'm using a Foreach loop to achieve it.

The problem is that on every single button, I get to load the same scene. It does list my levels from 1 to N but the onclick does not seem to be working fine! I've tried doing a for loop instead foreach but it doesn't work either.

int i = 0;
        foreach(GameObject level in levels)
        {
            level.GetComponent<Button>().onClick.AddListener(() => SceneManager.LoadScene(i + 1));
            i++;
        }

解决方案

You've created a closure on a loop variable. A common pitfall, for sure. A suitable explanation and remedy for this kind of problem already exists on StackOverflow.

When you use the symbol i, it is essentially a reference to the one and only i that existed outside of your loop. Its value, by the time any of the listeners get invoked, will be the value it had at the end of the loop, which, in your case, would be the number of levels you have.

To avoid this, you need to use the value of i, not a reference to the variable. You can do this by creating a new variable that will have scope unique to one iteration of the loop and passing in that new variable's value. Basically a copy of i is what you need.

The essence of the necessary change would be:

int i = 0;
foreach(GameObject level in levels)
{
    int copy_of_i = i;
    level.GetComponent<Button>().onClick.AddListener(() => SceneManager.LoadScene(copy_of_i + 1));
    i++;
}

这篇关于foreach 循环给 Unity 中的按钮赋值的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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