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

Unity C#中如何通过字符串变量名动态获取对应变量内容

可行性说明

该需求可实现。你当前调用ExampleText.SetText(A)仅输出"a000_7"本身,是因为传入的参数是变量A存储的字符串值,C#不会自动将字符串解析为同名变量的引用,因此无法直接获取对应变量存储的内容。

推荐实现方案(优先选用)

采用字典做键值映射是这类场景的最优实现,无额外性能损耗、编译期可排查大部分错误,维护成本低:

  • 初始化阶段将所有a000_x格式的字符串变量,以「变量名-变量存储的文本」的配对形式存入Dictionary<string, string>
  • 取值时直接以变量A的存储值为key,从字典中取出对应文本传入SetText即可

代码示例:

using System.Collections.Generic;
using UnityEngine;

public class TextMapping : MonoBehaviour
{
    // 文本映射字典
    private readonly Dictionary<string, string> _textMap = new Dictionary<string, string>();

    // 原有零散定义的字符串变量,可根据需求在Inspector或代码中赋值
    public string a000_1 = "文本1内容";
    public string a000_2 = "文本2内容";
    public string a000_3 = "文本3内容";
    // 其余a000_x变量按相同格式定义即可

    private void Awake()
    {
        // 初始化时注册所有变量到字典,nameof()可以自动获取变量名字符串,避免硬拼写错误
        _textMap.Add(nameof(a000_1), a000_1);
        _textMap.Add(nameof(a000_2), a000_2);
        _textMap.Add(nameof(a000_3), a000_3);
        // 其余变量按相同格式注册
    }

    /// <summary>
    /// 根据变量名字符串设置目标文本
    /// </summary>
    /// <param name="variableName">变量A存储的名称值,比如"a000_7"</param>
    public void SetMappedText(string variableName)
    {
        if (_textMap.TryGetValue(variableName, out string targetContent))
        {
            ExampleText.SetText(targetContent);
        }
        else
        {
            Debug.LogWarning($"未找到对应名称的文本:{variableName}");
        }
    }
}

调用时直接执行SetMappedText(A)即可实现需求,当A值为"a000_7"时,只要字典中注册了对应key,就会自动取出a000_7变量存储的内容传入文本组件。

备选方案(非特殊需求不推荐)

如果不想手动维护字典的注册逻辑,可以使用C#反射机制在运行时根据字符串查找同名字段获取值,但该方案性能远低于字典实现,且变量名拼写错误无法在编译阶段发现,容易出现运行时异常。
代码示例:

using System.Reflection;
using UnityEngine;

public class ReflectionTextTool : MonoBehaviour
{
    // 原有a000_x系列字符串变量
    public string a000_1 = "文本1内容";
    public string a000_2 = "文本2内容";
    // 其余变量按相同格式定义

    public void SetTextWithReflection(string variableName)
    {
        // 查找当前类下对应名称的公共实例字符串字段
        FieldInfo targetField = GetType().GetField(variableName, BindingFlags.Public | BindingFlags.Instance);
        if (targetField != null && targetField.FieldType == typeof(string))
        {
            string content = targetField.GetValue(this) as string;
            ExampleText.SetText(content);
        }
        else
        {
            Debug.LogWarning($"反射查找文本失败,不存在字段:{variableName}");
        }
    }
}

补充提示:如果这批a000_x的文本属于配置类、多语言类内容,更推荐将所有文本存入ScriptableObject或CSV/JSON配置表,无需手动定义零散变量,批量增删改查效率更高。

内容的提问来源于stack exchange,提问作者Seasick FRANCY

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 20:57:19