using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GenerateUIButtons : MonoBehaviour
{
public GameObject buttonPrefab;
public GameObject parent;
public int numberOfButtons;
public float spaceBetweenButtons;
private Button[] buttons;
// Start is called before the first frame update
void Start()
{
buttons = new Button[7];
for (int i = 0; i < Rotate.names.Length; i++)
{
GameObject newButton = Instantiate(buttonPrefab);
newButton.name = Rotate.names[i];
newButton.transform.SetParent(parent.transform, false);
buttons[i] = newButton.GetComponent<Button>();
buttons[i].onClick.AddListener(() => ButtonClicked(i));
}
}
void ButtonClicked(int buttonNo)
{
Debug.Log("Clicked On " + buttons[buttonNo]);
}
// Update is called once per frame
void Update()
{
}
}
我在行上遇到异常:
Debug.Log("Clicked On " + buttons[buttonNo]);
IndexOutOfRangeException:索引超出了数组的范围
我想做的是,当我单击其中一个按钮时,它将在ButtonClicked内执行相同的操作。
答案 0 :(得分:2)
这是一个闭包问题,请不要使用循环值创建闭包,而是先将值分配给另一个局部变量。
for (int i = 0; i < Rotate.names.Length; i++)
{
...
int j = i;
buttons[i].onClick.AddListener(() => ButtonClicked(j));
}