在使用代碼給Text賦值時,且文本有多段,并需要根據(jù)實(shí)際文本高度適配Text組件的高度時,可以使用以下方法:
//Text文本
public TextMeshProUGUI text;
void Start()
{
//代碼賦值文本
text.text = "好!\n很好!\n非常好!";
//獲取文本的高度
float preferredHeight = text.preferredHeight;
//獲取文本的RectTransform
RectTransform rectTransform = text.GetComponent<RectTransform>();
//組件高度根據(jù)實(shí)際文本高度自適應(yīng)
rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, preferredHeight);
}
設(shè)置前:
文本超出了組件框了。
設(shè)置后:
文章來源:http://www.zghlxwxcb.cn/news/detail-774277.html
文本有多高,組件就有多高。文章來源地址http://www.zghlxwxcb.cn/news/detail-774277.html
到了這里,關(guān)于Unity 代碼控制Text自適應(yīng)文本高度的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!