unity3d根據字符串讀取屬性.


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM