- Home /
Question by
indoflaven · Dec 30, 2017 at 09:14 PM ·
buttonsonclick
How to dynamically create buttons with unique onClick events
I'm trying to dynamically create a series of buttons that go to each go to a specific stage in my game. So if there are 10 stages there would be 10 button labeled 1-10 and which each go the labeled stage when clicked. The following code correctly creates and labels the necessary buttons. However when clicked all the buttons go to the last stage. So if there are 10 stages all buttons go to stage 10 despite individually setting the onClick.AddLister which a unique argument for each button. What am I doing wrong? Thanks in advance for the help! -Mike
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Menu : MonoBehaviour {
public GameObject stageSelectButtonPrefab;
public GameObject stageSelectUI;
private void Awake()
{
for(int i = 0; i < SceneManager.sceneCountInBuildSettings; ++i)
{
GameObject newButton = Instantiate(stageSelectButtonPrefab);
newButton.transform.SetParent(stageSelectUI.transform);
int stageNum = i + 1;
newButton.GetComponentInChildren<Text>().text = stageNum.ToString();
newButton.GetComponent<Button>().onClick.AddListener( () => { stageSelectOnClick(i); } );
}
}
public void stageSelectOnClick(int stageNum)
{
SceneManager.LoadSceneAsync(stageNum-1);
}
}
Comment