Unity中如何为反射获取的变量执行增加值操作?
解决方案
要通过反射实现字段的增量操作,你需要先读取字段当前值,计算增量后再写回字段——直接对FieldInfo对象用+=是无效的(它是字段的元数据对象,不是字段值)。以下是修改后的代码:
public class OreMine : MonoBehaviour { [SerializeField] string VariableName; void OnCollisionEnter2D(Collision2D col) { if(col.gameObject.tag == "Player") { // 获取Inventory类型的指定字段 var fieldInfo = typeof(Inventory).GetField(VariableName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); if (fieldInfo == null) { Debug.LogError($"找不到Inventory类中的字段: {VariableName}"); return; } // 获取字段所属实例:静态字段传null,实例字段取玩家身上的Inventory组件 object inventoryInstance = fieldInfo.IsStatic ? null : col.gameObject.GetComponent<Inventory>(); if (!fieldInfo.IsStatic && inventoryInstance == null) { Debug.LogError("玩家身上未找到Inventory组件"); return; } // 读取当前字段值并转为整数(若为其他数值类型,可调整转换逻辑) int currentValue = (int)fieldInfo.GetValue(inventoryInstance); // 计算增量后的值 int newValue = currentValue + 1; // 将新值写回字段 fieldInfo.SetValue(inventoryInstance, newValue); Destroy(gameObject); } } }
关键说明
FieldInfo.GetValue():用于读取字段当前值,静态字段传null,实例字段传对应类的实例。FieldInfo.SetValue():将计算后的新值写回字段,参数规则和GetValue一致。- 你提到的
SerializationInfo.AddValue方法和反射完全无关,它是序列化场景下用来添加数据的API,仅适用于序列化操作,不适合当前需求。
通用数值类型兼容(可选)
如果字段可能是float、long等其他数值类型,可以用更通用的方式处理:
// 读取当前值并转为IConvertible接口 IConvertible currentValue = (IConvertible)fieldInfo.GetValue(inventoryInstance); // 计算增量(这里以加1为例,可根据需求调整) object newValue = currentValue.ToDouble(null) + 1; // 转换回字段原始类型后写回 newValue = Convert.ChangeType(newValue, fieldInfo.FieldType); fieldInfo.SetValue(inventoryInstance, newValue);
内容的提问来源于stack exchange,提问作者ReoCyan
相关产品推荐
相关产品推荐

