【发布时间】:2021-07-05 20:14:16
【问题描述】:
我的场景包含两个对象 - 第一个是 DataHolder 对象,它包含一个带有单个整数的简单脚本,我在编辑器中将其设置为 5。第二个是 DataReader 类,我想用它从分配给 DataHolder 的脚本中访问“x”的值。
重要的是,在 DataReader 类中,我只有对 Data 脚本和我想要的变量字符串的引用。特别是,我不是在寻找像“dataScript.x”这样的答案,因为我正在寻找的特定属性名称将由用户选择,所以我不能这样硬编码。
[我的场景]
[数据持有者对象]
[数据读取器对象]
这是分配给 DataHolder 的 Data 脚本中的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Data : MonoBehaviour
{
public int x;
}
这是分配给 DataReader 的 DataReader 脚本中的代码。我已经在编辑器中分配了脚本和 propertyName,但我没有得到我期望的结果 - 我认为这会打印出 x 的值,但它却打印出“未找到”。:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Reflection;
using UnityEditor;
using System;
public class DataReader : MonoBehaviour
{
public UnityEngine.Object script;
public string propertyName;
void Start(){
Type scriptClass = script.GetType();
PropertyInfo[] properties = scriptClass.GetProperties();
bool found = false;
foreach(var property in properties){
if(property.Name == propertyName){
Debug.Log("The value was: " + property.GetValue(script).ToString());
found = true;
}
else{
}
}
if(!found){
Debug.Log("Not found.");
}
}
}
如何从 DataReader 的 Data 脚本中访问 x 的值,记住我真的在寻找通过名称字符串从 Data 中访问任意命名字段的能力?
【问题讨论】:
-
我相信你需要
scripClass.GetFields()方法而不是GetProperties()。