使用脚本更改按钮标签的字体(TextMesh Pro)



我想使用脚本来动态更改Unity中特定按钮标签的字体。然而,我的努力没有奏效。

我创造了一个简单的游戏。游戏界面在画布上有多个按钮,每个按钮上都有独特的文本标签。按钮是带有子元素(text-TextMeshPro(的画布元素(UI按钮(,该子元素为每个按钮提供文本标签。

在下面的代码示例中,除了最后一整行开始的"0"之外,所有代码都有效;buttonLabelText.font=";。例如,我可以使用其余的代码轻松地更改按钮的内容(更改按钮文本(。但是,我无法更改字体(或进行其他字体操作,如更改字体大小(。

其他信息:以下代码没有引发任何错误。我正在使用TextMeshPro。所需的字体位于以下文件夹中:Assets>TextMesh Pro>资源>字体&材料。字体以SDF格式保存。

附加上下文:我想通过脚本更改字体,因为游戏UI上有多个按钮,所有这些按钮都会在特定时间更改字体。因此,该脚本可以让我更容易地指定哪些按钮应该在特定时间更改字体。

有什么潜在的解决方案吗?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class FontManipulation : MonoBehaviour {
public TMP_FontAsset ChillerSDF; // ChillerSDF is the font I want for the button label text.
private TextMeshProUGUI buttonLabelText; // buttonLabelText is the actual text within the button label
void Start() {
TextMeshProUGUI buttonLabelText = GameObject.Find("ButtonLabel").GetComponent<TextMeshProUGUI>(); // This code finds the correct button label among multiple button labels in the scene, and grabs the TextMesh Pro GUI. This code works (I can use it to change what the text says, for example).
buttonLabelText.font = ChillerSDF; // This code should change the font to the desired font, but does not work.
}
}

我遇到了和你一样的问题,我通过获取TMP_Text而不是TextMeshProUGUI 解决了这个问题

public TMP_FontAsset ChillerSDF; 
private TMP_Text buttonLabelText; //TMP_Text instead of TextMeshProUGUI

void Start() { 
TMP_Text buttonLabelText = GameObject.Find("ButtonLabel").GetComponent<TMP_Text>();
buttonLabelText.font = ChillerSDF; // This code should work now
}

最新更新