using UnityEngine; using UnityEngine.UI; using TMPro; [ExecuteAlways] // 에디터 모드에서도 스크립트 실행 public class DynamicBackground : MonoBehaviour { public TextMeshProUGUI tmpText; // TextMeshProUGUI 오브젝트 RectTransform backgroundRect; // 배경 이미지의 RectTransform public Vector2 padding; // 배경에 추가할 패딩 (텍스트 주변의 여백) void Start() { backgroundRect = GetComponent(); // 처음에 한번 업데이트 UpdateBackgroundSize(); } void Update() { // 매 프레임마다 텍스트 크기 변화에 맞춰 배경 크기 업데이트 UpdateBackgroundSize(); } void UpdateBackgroundSize() { if (backgroundRect == null) backgroundRect = GetComponent(); if (tmpText != null) { // 텍스트의 실제 크기 (preferred size) 가져오기 float width = tmpText.preferredWidth; float height = tmpText.preferredHeight; // 텍스트의 크기 + 패딩으로 배경 크기 설정 backgroundRect.sizeDelta = new Vector2(width + padding.x, height + padding.y); } } }