【发布时间】:2016-07-15 00:11:13
【问题描述】:
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
【问题讨论】:
-
尝试将 Current.Nodes.ForEach( n => Debug.Log( n.name ) ); 行放入 lambda 表达式中,看看两个节点是否还有你期望的名字。也许你稍后在代码的其他地方覆盖它们而不知道。
-
不。我期望的名字。
-
这段代码在 couroutine 中。这有意义吗?
-
尝试将 button. 放在 lambda 表达式中的 GetComponentInChildren
().text 之前。也许您甚至没有从按钮中获取孩子,而是从该代码所在的对象中获取。所以该行看起来像这样: Debug.Log( button.GetComponentInChildren().text ); -
是的,这是不对的,但现在它是所有按钮上的 node1 输出。同样的问题。