2017-07-22 31 views
0

目前我使用C#在Unity中開發了一些東西。如何使用c獲取本地對象變量#

比方說,我有在下面定義的變量,這些腳本是在同一個文件和橙色是預製

private GameObject orange; 
private GameObject avocado; 

然後,我想訪問/得到它的對象通過名稱/字符串 (因爲未來的發展將使用很多動態變量),我已經嘗試過使用GetType()但沒有運氣,例如:

void Awake() { 

orange = (GameObject)Resources.Load ("fruits/Orange", typeof(GameObject)); //getting Orange Prefab 
avocado = (GameObject)Resources.Load ("fruits/Avocado", typeof(GameObject)); //getting Avocado Prefab 

} 

void Start() { 

//Here, i try to get orange/avocado/other fruitname by string 
GameObject orangeObj = (GameObject) this.GetType().GetField("orange").GetValue(this); 

GameObject _orange = Instantiate (orangeObj, new Vector3 (elem_1_pos_x, elem_1_pos_y, 0), Quaternion.identity) as GameObject; 

} 

上面的代碼會給我錯誤:「對象引用未設置爲對象的實例」,這意味着它仍然沒有得到橙色的對象。

任何想法或建議?

+0

@RomanoZumbé我嘗試閱讀/訪問'橙Prefab'的字符串,但如果你有更好的方法,請讓我知道... – anunixercoder

+0

@RomanoZumbé不能這樣。在'Start()'方法中,我想通過字符串獲得Orange'GameObject'。在未來,它將是動態的。即「葡萄」,「鱷梨」等...... – anunixercoder

+0

「GetField」默認只獲取公共靜態和實例字段。你需要專門告訴它尋找私人領域:https://stackoverflow.com/questions/95910/find-a-private-field-with-reflection/95973#95973 – 31eee384

回答

1

通過問題評論中的建議。我找到了答案,更改:

GameObject orangeObj = (GameObject) this.GetType().GetField("orange").GetValue(this); 

GameObject orangeObj = (GameObject) this.GetType().GetField("orange", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);