Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么我的函数将10作为参数传递?_C#_Unity3d - Fatal编程技术网

C# 为什么我的函数将10作为参数传递?

C# 为什么我的函数将10作为参数传递?,c#,unity3d,C#,Unity3d,我想在Unity中的按钮中添加onClick侦听器,C#。 我有一系列的按钮。我试图循环遍历该数组,并且为每个按钮添加一个onClick侦听器,该侦听器调用一个带有索引参数的函数。 在该函数中,我打印出函数接收到的参数。 然而,当我点击其中一个按钮时,每次都会得到10作为输出 for(int i = 0; i < roleButtons.Length; ++i) { roleButtons[i].onClick.AddListener(delegate { changeEquipm

我想在Unity中的按钮中添加onClick侦听器,C#。 我有一系列的按钮。我试图循环遍历该数组,并且为每个按钮添加一个onClick侦听器,该侦听器调用一个带有索引参数的函数。 在该函数中,我打印出函数接收到的参数。 然而,当我点击其中一个按钮时,每次都会得到10作为输出

for(int i = 0; i < roleButtons.Length; ++i) {
    roleButtons[i].onClick.AddListener(delegate { changeEquipment(i); });
}

void changeEquipment(int index) {
    Debug.Log(index); //Here I got 10 as an output after every single click.
}
for(int i=0;i
您需要复制变量
i
locally这称为“闭包”。您将“i”变量作为闭包传递,这意味着所有按钮将从“i”接收相同的值,在for循环之后,该值为10。