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

posted @ 2014-07-24 16:04  reuyui  阅读(4455)  评论(1编辑  收藏  举报