using System; using TMPro; using UnityEngine; [ExecuteInEditMode] public class FixRectWidthByString : MonoBehaviour { public int minWidth = 40; private TextMeshProUGUI textComp; private void Awake() { textComp = GetComponentInChildren(); } private void OnEnable() { SetRectSize(); } private float GetTextWidth() { int width = 0; if (textComp != null) { var txt = textComp.text; var font = textComp.font.sourceFontFile; CharacterInfo characterInfo; font.RequestCharactersInTexture(txt, font.fontSize); for (int i = 0; i < txt.Length; i++) { font.GetCharacterInfo(txt[i], out characterInfo, font.fontSize); width += characterInfo.advance; } } return width + minWidth; } [ContextMenu("激活")] private void SetRectSize() { GetComponent().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,GetTextWidth()); } }