標籤:style 使用 re c 代碼 line type size
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