This repository has been archived on 2026-04-18. You can view files and clone it, but cannot push or open issues or pull requests.
Virtual-Memory-Demo/Assets/Scripts/UI/TimelineLogItemAutoSize.cs

53 lines
1.8 KiB
C#

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<TMP_Text>();
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<LayoutElement>();
if (layoutElement != null)
{
layoutElement.preferredWidth = width;
layoutElement.preferredHeight = height;
}
}
}
}