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

Unity中将自定义枚举值赋值给TextMeshPro的fontStyle时报错如何解决

错误原因
  • 你自定义的fontStyleEnum与TextMeshPro内置的FontStyles枚举是完全独立的两个类型,无法直接赋值给TMP文本的fontStyle属性
  • 代码中FontStyles.fontStyle.value属于非法写法:TMP的FontStyles是静态枚举类,不存在名为fontStyle的成员,也没有value属性。
修复方案

方案1(推荐):直接使用TMP自带的FontStyles枚举

无需自定义枚举,直接声明FontStyles类型的公共变量即可,Inspector会自动展示所有可选字体样式,代码修改如下:

using UnityEngine;
using TMPro;

public class TextScript : MonoBehaviour {
    public TMP_Text textMesh; 
    // 直接使用TMP自带的字体样式枚举
    public FontStyles fontStyle;
    
    public void Start(){
        textMesh.fontStyle = fontStyle;
    }
}

方案2:保留自定义枚举,添加映射逻辑

如果必须保留你自定义的fontStyleEnum,可以在赋值前做枚举值的转换,代码修改如下:

using UnityEngine;
using TMPro;

public class TextScript : MonoBehaviour {
    public enum fontStyleEnum 
    {
        Bold, 
        Underline, 
        Italic
    };

    public TMP_Text textMesh; 
    public fontStyleEnum fontStyle;
    
    public void Start(){
        // 将自定义枚举映射为TMP对应的字体样式
        switch (fontStyle)
        {
            case fontStyleEnum.Bold:
                textMesh.fontStyle = FontStyles.Bold;
                break;
            case fontStyleEnum.Underline:
                textMesh.fontStyle = FontStyles.Underline;
                break;
            case fontStyleEnum.Italic:
                textMesh.fontStyle = FontStyles.Italic;
                break;
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:48:06