You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#如何打印名称存储在字符串变量中的变量的值

解决方案

C# 是静态强类型编译语言,没有 PHP 那种直接通过字符串形式的变量名访问局部变量的语法,要实现该需求可以用两种方案:


方法1:反射实现(通用场景)

前提要求:需要查询的 int、float、string 等变量必须是类的成员字段/属性,局部变量编译后会被优化掉元数据,无法通过字符串查询。
实现代码如下:

using UnityEngine;
using System.Reflection;

public class VariablePrinter : MonoBehaviour
{
    // 要查询的变量必须是类的成员
    public int Ronaldo = 7;
    public int Messi = 10;
    public string Player = "Messi";

    void Start()
    {
        PrintValueOfString(Player); // 运行后控制台输出 10
    }

    void PrintValueOfString(string variableName)
    {
        Type currentType = this.GetType();
        // 先查找字段成员
        FieldInfo targetField = currentType.GetField(
            variableName, 
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
        );
        if (targetField != null)
        {
            Debug.Log(targetField.GetValue(this).ToString());
            return;
        }
        // 没找到字段再查找属性成员
        PropertyInfo targetProperty = currentType.GetProperty(
            variableName, 
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
        );
        if (targetProperty != null)
        {
            Debug.Log(targetProperty.GetValue(this).ToString());
            return;
        }
        Debug.LogWarning($"未找到名为 {variableName} 的成员");
    }
}

参数调整说明:

  • 需要查询静态成员时,将 BindingFlags.Instance 替换为 BindingFlags.Static 即可
  • 需要仅查询公开成员时,删除 BindingFlags.NonPublic 参数即可

方法2:字典映射实现(高性能场景)

如果需要查询的变量是预先固定的,更推荐用字典做映射,性能远高于反射,适合频繁调用的场景:

using UnityEngine;
using System.Collections.Generic;

public class VariablePrinter : MonoBehaviour
{
    public int Ronaldo = 7;
    public int Messi = 10;
    public string Player = "Messi";

    private Dictionary<string, object> _variableMap;

    void Awake()
    {
        // 初始化映射字典
        _variableMap = new Dictionary<string, object>
        {
            {nameof(Ronaldo), Ronaldo},
            {nameof(Messi), Messi}
        };
    }

    void PrintValueOfString(string variableName)
    {
        if (_variableMap.TryGetValue(variableName, out var value))
        {
            Debug.Log(value.ToString());
            return;
        }
        Debug.LogWarning($"未找到名为 {variableName} 的变量");
    }

    // 如果变量值会更新,需要同步更新字典的值,示例:
    void UpdateMessiValue(int newValue)
    {
        Messi = newValue;
        _variableMap[nameof(Messi)] = newValue;
    }
}

内容的提问来源于stack exchange,提问作者Ahmed Al-Gammal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:36:01