请先看对象层级视图
/// <summary>
/// 选择关卡的内容对象
/// </summary>
public Transform Transform_levelContent;
// Start is called before the first frame update
void Start()
{
ButtonsListenerSetUp();
}
private void ButtonsListenerSetUp()
{
if (Button_backMainScene) Button_backMainScene.onClick.AddListener(ClickButton_backMain);
if (Transform_levelContent)
{
for (int i = 0; i < Transform_levelContent.childCount; i++)
{
Transform_levelContent.GetChild(i).name = (i + 1).ToString();
Transform_levelContent.GetChild(i).Find("Text").GetComponent<Text>().text = (i + 1).ToString();
string level = (i + 1).ToString(); //注意这里必须要先在这里赋给变量
Transform_levelContent.GetChild(i).GetComponent<Button>().onClick.AddListener(() => {
ClickButton_levelChoose(level);
});
/*这样写会得不到正确的值
Transform_levelContent.GetChild(i).GetComponent<Button>().onClick.AddListener(() => {
ClickButton_levelChoose((i + 1).ToString());
});
*/
}
}
}