2016-01-19 21 views
0

在下面的代碼,該類ButtonScript有一個名爲buttonObj字段,類型爲GameObject如何將GetField()的結果轉換爲可用對象?

var button = gameObject.AddComponent<ButtonScript>(); 
var obj = button.GetType().GetField("buttonObj"); 
Debug.Log(obj); //prints UnityEngine.GameObject 
Debug.Log(obj.name); //compilation error 

上最後一行的錯誤是:

Type 'System.Reflection.FieldInfo' does not contain a definition for 'name'... 

它爲什麼說這是一個GameObject時它已記錄,但是當我嘗試使用它時,它說這是一個FieldInfo對象?

我怎樣才能得到它,以便我可以像GameObject那樣對待它?

+0

的'的'ToString'可能FieldInfo'返回的字符串。 –

+0

這是一個簡單的錯字?屬性名稱是'Name',而不是'name'。 –

+0

@YacoubMassad否,小寫'name'是對的http://docs.unity3d.com/ScriptReference/Object-name.html – Houseman

回答

0

obj變量的類型是FieldInfo而不是GameObject

FieldInfo類表示有關buttonObj字段的元數據信息。它不包含它的價值。

要得到它的價值,你必須使用GetValue方法是這樣的:

var button = gameObject.AddComponent<ButtonScript>(); 

var field = button.GetType().GetField("buttonObj"); 

//Assuming that the type of the field is GameObject 
var obj = (GameObject)field.GetValue(button); 

var name = obj.name; 
相關問題