2026-01-12 02:40:14 +08:00

36 lines
1.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using TMPro;
using UnityEngine;
using UnityEngine.UI;
//编辑器时也可以实时刷新看到
[ExecuteAlways]
public class ChatBubble : MonoBehaviour
{
public TextMeshProUGUI TextComponent;
public LayoutElement TextLayoutElement; // 对应Text物体上的LayoutElement组件
public float MaxWidth = 450f; // 气泡的最大宽度
public void SetText(string content)
{
// 1. 先重置约束,让文本以“自然长度”测量
TextLayoutElement.enabled = false;
TextComponent.text = content;
// 2. 强制刷新文本的网格数据,以便获取当前的理想宽度
TextComponent.ForceMeshUpdate();
// 3. 核心逻辑:获取文本单行显示的理想宽度
float preferredWidth = TextComponent.GetPreferredValues(content).x;
// 4. 判断逻辑
if (preferredWidth > MaxWidth)
{
// 如果单行超宽开启LayoutElement并限制宽度 -> 迫使文本换行
TextLayoutElement.enabled = true;
TextLayoutElement.preferredWidth = MaxWidth;
}
else
{
// 如果没超宽关闭LayoutElement -> 让Parent的ContentSizeFitter根据文本实际宽度收缩
TextLayoutElement.enabled = false;
}
}
}