using TMPro; using UnityEngine; using UnityEngine.UI; namespace VMdemo.UI { [RequireComponent(typeof(RectTransform))] public class TimelineLogItemAutoSize : MonoBehaviour { [SerializeField] private TMP_Text textComponent; [SerializeField] private float horizontalPadding = 20f; [SerializeField] private float verticalPadding = 12f; [SerializeField] private bool clampToParentWidth = true; [SerializeField] private float minWidth = 80f; [SerializeField] private float minHeight = 30f; public void RefreshLayout() { var text = textComponent != null ? textComponent : GetComponent(); var root = (RectTransform)transform; if (text == null) { return; } float maxWidth = float.PositiveInfinity; if (clampToParentWidth && root.parent is RectTransform parentRect) { maxWidth = Mathf.Max(1f, parentRect.rect.width - horizontalPadding); } var preferred = text.GetPreferredValues(text.text, maxWidth, 0f); var width = Mathf.Max(minWidth, preferred.x + horizontalPadding); var height = Mathf.Max(minHeight, preferred.y + verticalPadding); if (clampToParentWidth && root.parent is RectTransform p) { width = Mathf.Min(width, Mathf.Max(minWidth, p.rect.width)); } root.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, width); root.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height); var layoutElement = GetComponent(); if (layoutElement != null) { layoutElement.preferredWidth = width; layoutElement.preferredHeight = height; } } } }