이 코드를 작성하여 장면의 큐브 수를 확인하고 각 큐브에 대해 동적으로 단추를 만듭니다. 단추를 클릭하면 큐브의 위치가 표시됩니다. 그러나이 코드를 실행하면 마지막 큐브 만 실행됩니다 위치는 shown.What 나는 당신의 람다 함수에서 잘못된 여기큐브의 위치를 버튼에 지정하려면 클릭하십시오.
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() {
}
}
가능한 중복 http://stackoverflow.com/questions/4155691/c-sharp-lambda-local-variable-value-not- 당신이 생각할 때 찍은) – sokkyoku