C# 通过脚本变量名称的字符串访问该脚本变量
我的场景包含两个对象——第一个是DataHolder对象,它包含一个简单的脚本,其中包含一个整数,我在编辑器中将其设置为5。第二个是DataReader类,我想使用它从分配给DataHolder的脚本中访问x的值 重要的是,在DataReader类中,我只有对数据脚本和所需变量字符串的引用。特别是,我不是在寻找像dataScript.x这样的答案,因为我要寻找的特定属性名称将由用户选择,所以我不能像那样硬编码 [我的场景] [数据持有者对象] [数据读取器对象] 这是分配给数据持有者的数据脚本中的代码:C# 通过脚本变量名称的字符串访问该脚本变量,c#,unity3d,types,C#,Unity3d,Types,我的场景包含两个对象——第一个是DataHolder对象,它包含一个简单的脚本,其中包含一个整数,我在编辑器中将其设置为5。第二个是DataReader类,我想使用它从分配给DataHolder的脚本中访问x的值 重要的是,在DataReader类中,我只有对数据脚本和所需变量字符串的引用。特别是,我不是在寻找像dataScript.x这样的答案,因为我要寻找的特定属性名称将由用户选择,所以我不能像那样硬编码 [我的场景] [数据持有者对象] [数据读取器对象] 这是分配给数据持有者的数据脚本中
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Data : MonoBehaviour
{
public int x;
}
这是分配给DataReader的DataReader脚本中的代码。我已经在编辑器中分配了脚本和propertyName,但我没有得到预期的结果-我以为这会打印出x的值,但它打印出的是Not found.:
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的数据脚本中访问x的值,请记住,我实际上是在寻找通过名称字符串从数据中访问任意命名字段的能力
public class DataReader : MonoBehaviour
{
public UnityEngine.Object script;
public string propertyName;
void Start()
{
Type scriptClass = script.GetType();
FieldInfo[] fields = scriptClass.GetFields();
bool found = false;
foreach (var field in fields)
{
if (field.Name == propertyName)
{
Debug.Log("The value was: " + field.GetValue(script).ToString());
found = true;
}
else
{
}
}
if (!found)
{
Debug.Log("Not found.");
}
}
}
字段是存储数据的变量,属性是为私有字段提供读、写或计算的成员。很容易把他们弄糊涂。根据您希望使用此工具执行的操作,我还将研究。我相信您需要的是scripClass.GetFields方法,而不是GetProperties。