I’m creating buttons using a prefab and instantiate it by code.
I’m then trying to get each button to print their own number on click.
Right now, each button is only returning the same number “5”.
Is there an easy way to do that ?
Here is the code
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TESTGUI : MonoBehaviour {
public Canvas myCanvas;
public Button buttonPrefab;
private void printNumber(int myNumber)
{
Debug.Log (myNumber);
}
// Use this for initialization
void Start () {
for(int i=0; i<5; i++)
{
Button myButton = Instantiate(buttonPrefab) as Button;
myButton.transform.SetParent(myCanvas.transform, false);
myButton.transform.position = new Vector3(250f, 50f + (40f * i), 0f);
myButton.onClick.AddListener(() => printNumber(i));
}
}
}