2016-09-06 4 views
1

このコードを書いて、シーン内のキューブの数を特定し、キューブごとに動的にボタンを作成します。ボタンをクリックすると、キューブの位置が表示されます。このコードを実行すると、最後のキューブ位置は私がここで間違ってあなたのラムダ関数でキューブの位置をボタンのクリックに統一して割り当てますか?

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

をしていshown.Whatです:

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

aは前に宣言された変数への参照です。クロージャは、使用する変数への参照を取得します。 aはforループの外側にあると宣言しています。ループするたびに同じ変数が使用され、クロージャは同じ参照を取得します。

ループ内に変数を宣言すると、その変数を実行するたびに新しいメモリが取得され、異なるメモリチャンクに参照されます。

以下は、(テスト済みの)問題を解決します。

string b = a; 
m.onClick.AddListener(() => 
{ 
    Debug.Log(b); 
} 
[あなたが考えたときに取られていないC#のラムダ、ローカル変数の値は?](の
+0

それでも値は1つだけです –

関連する問題