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 中执行相同的操作。
这是一个闭包问题,不要使用循环值来创建闭包,先将值赋给另一个局部变量。
for (int i = 0; i < Rotate.names.Length; i++)
{
...
int j = i;
buttons[i].onClick.AddListener(() => ButtonClicked(j));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句