【问题标题】:Access script variable by the string of it's name unity通过名称 unity 的字符串访问脚本变量
【发布时间】: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()

标签: c# unity3d types


【解决方案1】:
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.");
        }
    }
}

字段是存储数据的变量,属性是为私有字段提供读、写或计算的成员。很容易让他们感到困惑。根据你想用这个工具做什么,我也会研究BindingFlags

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 2023-01-09
    • 2022-07-22
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多