unity3d根据字符串读取属性.

本文详细介绍了Unity3D中如何正确使用Field与Property,通过具体实例展示了如何获取和设置类的属性值,并提供了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/reuyui/p/3865836.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值