foreach中的AddListener

时间:2016-07-15 00:11:14

标签: c# unity3d foreach lambda

在foreach声明中突然出现lambda问题:

IEnumerator RefreshNextFrame( Part Current )
{
    yield return null;
    if( Current.Nodes == null )
        yield break;
    Current.Nodes.ForEach( n => Debug.Log( n.name ) );//outputs node0, node1
    for( int i = 0; i < Current.Nodes.Count; i++ )
    {
        Node node = Current.Nodes[i];
        Button button = Instantiate( Resources.Load<GameObject>( "Prefabs/Button" ) ).GetComponent<Button>();
        button.transform.SetParent( content );
        button.GetComponentInChildren<Text>().text = node.name;
        button.onClick.AddListener( delegate
        {
            Debug.Log( button.GetComponentInChildren<Text>().text );
        } );
    }
}

点击按钮始终输出node1

2 个答案:

答案 0 :(得分:0)

因为这段代码的所有内容都在couroutine中。这是答案http://answers.unity3d.com/answers/974195/view.html

答案 1 :(得分:0)

只需在每次迭代时分配一个新的局部变量,并将该局部变量用于AddListener。

EDIT 快速举例:

MyFunction将始终在此处获得100作为i的值:

for (int i=0; i<100; i++) {
    button.onClick.AddListener(() => MyFunction(i));
}

但如果你这样做,它将正常工作:

for (int i=0; i<100; i++) {
    int iLocal = i;
    button.onClick.AddListener(() => MyFunction(iLocal));
}