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

Godot静态类传参问题:通过按钮信号传递字段名获取对应值

解决方法

你当前代码里的Texts.name是在尝试访问Texts类中名为"name"的字段,而不是用参数name的字符串值去匹配对应的字段,所以根本取不到你想要的内容。下面给两种可行的实现方式:

方法一:使用反射(适合字段较多或动态新增的场景)

通过反射可以根据字符串名称获取静态类的字段值,代码如下:

using System.Reflection;

private void ChangeText(string name)
{
    Type textType = typeof(Texts);
    // 查找公开的静态字段
    FieldInfo targetField = textType.GetField(name, BindingFlags.Public | BindingFlags.Static);
    
    if (targetField != null && targetField.FieldType == typeof(string))
    {
        // 静态字段GetValue传入null即可
        this.Text = (string)targetField.GetValue(null);
        _animationPlayer.Play("showtext");
    }
    else
    {
        // 处理字段不存在的异常情况
        this.Text = "无效文本";
    }
}

方法二:使用字典映射(性能更高、更安全,适合字段固定的场景)

提前把字段名和对应值存入字典,后续直接通过键取值,避免反射的性能开销,同时更易维护:

using System.Collections.Generic;

// 定义字典存储字段名与文本的映射
private static Dictionary<string, string> _textLookup;

// 在初始化方法(比如Awake/Start)中填充字典
private void Awake()
{
    _textLookup = new Dictionary<string, string>
    {
        { "Info", Texts.Info },
        { "Objects", Texts.Objects }
        // 后续新增Texts字段时,在这里同步添加对应项即可
    };
}

private void ChangeText(string name)
{
    if (_textLookup.TryGetValue(name, out string targetText))
    {
        this.Text = targetText;
        _animationPlayer.Play("showtext");
    }
    else
    {
        this.Text = "无效文本";
    }
}

两种方法对比:

  • 反射无需手动维护映射关系,但运行时性能略低,且字段名拼写错误只会在运行时暴露;
  • 字典映射性能更好,类型更安全,字段名错误在编译阶段就能发现,但需要同步维护字典和Texts类的字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 12:47:41