我正在编写简单的动态gui按钮代码,我想知道1.和2.代码之间的区别(第一个工作错误,第二个很好)
AddGUIMenuEntry(...) - 第二个参数是按钮文本,第三个是按下按钮时将被调用的委托
容器是一个类
有两段代码:
1
foreach(var c in StandsManager.instance.containers) //array with Container objects with id 0 and 1
{
ProductsManager.instance.AddGUIMenuEntry(gui, "Spawn " + c.id.ToString(), //adds GUI button with text "Spawn 0" for first object and "Spawn 1" for second
() =>
{
StandsManager.instance.CreateContainer(c.id, this); //click first and second button do the same - they create Container with id 1 - wrong
}
);
}
2
for(int i = 0; i < StandsManager.instance.containers.Length; i++)
{
Container c = StandsManager.instance.containers[i];
ProductsManager.instance.AddGUIMenuEntry(gui, "Spawn " + c.id.ToString(),
() =>
{
StandsManager.instance.CreateContainer(c.id, this); //pressing first creates Container with id 0, pressing second creates Container with id 1 - good
}
);
}
我想这与变量范围有关。