I have written this code to identify the number of cubes in the scene and create a button dynamically for each cube.and when a button is clicked the position of a cube will be displayed.but when I run this code only the final cubes position is shown.What am I doing Wrong here
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class buttons : MonoBehaviour {
public GameObject MyButtonPrefab;
public RectTransform ParentPanel;
// Use this for initialization
int bpos = 143;
Button m;
string a;
void Start () {
//Debug.Log(GameObject.FindGameObjectWithTag("Cube").transform.position);
GameObject[] objects = GameObject.FindGameObjectsWithTag("Cube");
int x = GameObject.FindGameObjectsWithTag("Cube").Length;
Debug.Log(x);
for (int i = 0; i < objects.Length; i++)
{
bpos++;
a = objects[i].transform.position.ToString();
Debug.Log(a);
GameObject newButton = (GameObject)Instantiate(MyButtonPrefab, new Vector3(1, 1, 1), Quaternion.identity);
newButton.transform.SetParent(ParentPanel, false);
newButton.transform.localScale = new Vector3(1, 1, 1);
newButton.transform.position = new Vector3(0, bpos, 0);
newButton.name = "Camerapos";
m = newButton.GetComponent<Button>();
m.onClick.AddListener(() =>
{
Debug.Log(a);
});
}
}
// Update is called once per frame
void Update () {
}
}