unity3d的對象有field, property.
一般要取得類的某個屬性時,要使用GetType().GetField(xxx);
許多教程都寫用property.(坑)
property 感覺是運行時的屬性.(not sure!)
ex:有個類xxx
public class xxx{
public int aaa = 5;
public string bbb = "test";
}
那么要取得xxx的aaa屬性,則應該先從xxx里讀取叫aaa的fieldinfo. 再從fieldinfo里取value.
完整代碼:
//檢查字段
public bool hasField(string fieldName)
{
return this.GetType().GetField(fieldName) != null;
}
xxx.hasField("aaa"); //true
xxx.hasField("ccc"); //false
//獲取字段類型
public Type getFieldType(string fieldName)
{
return this.GetType().GetField(fieldName).FieldType;
}
//獲取字段值
public object getFieldValue(string fieldName)
{
return this.GetType().GetField(fieldName).GetValue(this);
}
xxx.getFieldType("aaa"); //int
xxx.getFieldValue("aaa"); //5
//給某個字段設值.
public void setFieldValue(string field, object val)
{
Type Ts = this.GetType();
if (val.GetType() != Ts.GetField (field).FieldType) {
val = Convert.ChangeType(val, Ts.GetField(field).FieldType);
}
Ts.GetField (field).SetValue (this, val);
}
xxx.getFieldValue("aaa"); //5
xxx.setFieldValue("aaa",999);
xxx.getFieldValue("aaa"); //999