Unity中能否通过C#脚本为TextMeshPro文本字符串中的单词加粗?
在Unity中为TextMeshPro字符串指定单词设置加粗效果的两种方案
方法一:使用TextMeshPro富文本标签
TextMeshPro原生支持富文本语法,直接用<b>标签(等效于<strong>)包裹需要加粗的内容即可。注意要确保TextMeshProUGUI组件的Rich Text选项在Inspector面板中处于勾选状态,否则标签会被当作普通文本显示。
修改你的代码如下:
public string tempCurrentTeam = "CurrentTeam"; public string roundDivision = "Primary"; public string roundTitle = "Preliminary Round 1"; public TextMeshProUGUI RoundHeaderText; // ... RoundHeaderText.text = $"Active score for: <b>{tempCurrentTeam}'s</b> - {roundDivision} {roundTitle}";
也可以用传统字符串拼接方式实现:
RoundHeaderText.text = "Active score for: <b>" + tempCurrentTeam + "'s</b> - " + roundDivision + " " + roundTitle;
方法二:使用多个TextMeshProUGUI文本块
如果不想依赖富文本,可拆分内容到三个独立的TMP文本块中,通过组件本身的样式设置实现加粗:
- 在场景中创建三个
TextMeshProUGUI对象,给它们的父物体添加Horizontal Layout Group组件,让文本块自动横向排列保证排版整齐; - 分别为三个文本块赋值并设置样式:
public string tempCurrentTeam = "CurrentTeam"; public string roundDivision = "Primary"; public string roundTitle = "Preliminary Round 1"; // 分别引用三个文本块 public TextMeshProUGUI prefixText; public TextMeshProUGUI teamNameText; public TextMeshProUGUI suffixText; // ... prefixText.text = "Active score for: "; teamNameText.text = $"{tempCurrentTeam}'s"; // 两种方式设置加粗:要么在Inspector里把teamNameText的Font Style设为Bold,要么通过代码设置 teamNameText.fontStyle = FontStyles.Bold; suffixText.text = $" - {roundDivision} {roundTitle}";
这种方式可单独控制每个部分的字号、颜色等样式,后期调整更灵活。
内容的提问来源于stack exchange,提问作者Br Barry
相关产品推荐
相关产品推荐

