我编写了这段代码来识别场景中的立方体数量,并为每个立方体动态创建一个按钮。当点击一个按钮时,将显示一个立方体的位置。但是当我运行此代码时,只有最后一个立方体位置显示。我在做什么错了
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 () {
}
}
答案 0 :(得分:0)
在你的lambda函数中:
m.onClick.AddListener(() =>
{
Debug.Log(a);
}
a
是对之前声明的变量的引用。闭包捕获对它们使用的变量的引用。你已经在for循环之外声明了a
,所以每次循环它时,都会使用相同的变量,你的闭包会捕获相同的引用。
如果在循环中声明一个变量,每次运行它时都会得到一个新的内存,并且会引用不同的内存块。
以下修复了您的问题(已测试)。
string b = a;
m.onClick.AddListener(() =>
{
Debug.Log(b);
}