using TMPro; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(RectTransform))] public class AutoResizeImage : MonoBehaviour { public TMP_Text contentText; private RectTransform backgroundImageRect; void Start() { backgroundImageRect = GetComponent(); AdjustImageWidth(); } void Update() { AdjustImageWidth(); } void AdjustImageWidth() { // 获取 Text 组件的首选宽度 float preferredWidth = contentText.preferredWidth; // 设置 Image 的宽度为 Text 的首选宽度,加上一些 padding(假设为 20) backgroundImageRect.sizeDelta = new Vector2(preferredWidth + (contentText.text == "" ? 0 : 30), backgroundImageRect.sizeDelta.y); contentText.GetComponent().sizeDelta = new Vector2(preferredWidth + (contentText.text == "" ? 0 : 30), 52); } }