2016-09-06 2 views
1

이 코드를 작성하여 장면의 큐브 수를 확인하고 각 큐브에 대해 동적으로 단추를 만듭니다. 단추를 클릭하면 큐브의 위치가 표시됩니다. 그러나이 코드를 실행하면 마지막 큐브 만 실행됩니다 위치는 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() { 

    } 



} 
+0

가능한 중복 http://stackoverflow.com/questions/4155691/c-sharp-lambda-local-variable-value-not- 당신이 생각할 때 찍은) – sokkyoku

답변

0

하고있는 중이 야된다

m.onClick.AddListener(() => 
{ 
    Debug.Log(a); 
} 

a 이전에 선언 된 변수에 대한 참조입니다. 클로저는 사용하는 변수에 대한 참조를 캡처합니다. a을 for 루프 외부에 선언 했으므로 반복 할 때마다 동일한 변수가 사용되며 클로저는 동일한 참조를 캡처합니다.

루프 내에서 변수를 선언하면이를 실행할 때마다 새로운 메모리가 생성되고 다른 메모리 덩어리로 참조가 이동합니다.

다음은 문제가 해결 된 테스트 결과입니다.

string b = a; 
m.onClick.AddListener(() => 
{ 
    Debug.Log(b); 
} 
[당신이 생각하는 경우 촬영하지 C#을 람다, 지역 변수 값?] (의
+0

여전히 단 하나의 가치를 제공합니다 –

관련 문제