Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This class must stay on the parent were the image used as background sits.
- // As child you have to have TextMeshProUGUI text.
- // Set the transform as centered, and as you wish for padding and stuff... That's it.
- // Will works automagically =)
- [ExecuteAlways]
- [RequireComponent(typeof(RectTransform))]
- public class ResizeBackgroundToText : MonoBehaviour
- {
- [Header("Riferimenti")]
- [Tooltip("Il componente TextMeshPro figlio.")]
- public TextMeshProUGUI text;
- [Tooltip("Il RectTransform di questo oggetto (il background). Si assegna da solo se lasciato vuoto.")]
- public RectTransform background;
- [Header("Limiti e Padding")]
- [Tooltip("Padding per ogni lato. X = sinistra/destra, Y = sopra/sotto.")]
- public Vector2 padding = new Vector2(20f, 10f);
- [Tooltip("La larghezza massima che questo elemento può raggiungere prima che il testo vada a capo.")]
- public float maxWidth = 500f;
- [Header("Editor")]
- public bool autoUpdateInEditor = true;
- void OnEnable()
- {
- if (background == null)
- {
- background = GetComponent<RectTransform>();
- }
- }
- void LateUpdate()
- {
- if (Application.isPlaying)
- {
- Resize();
- }
- #if UNITY_EDITOR
- else if (autoUpdateInEditor)
- {
- Resize();
- }
- #endif
- }
- #if UNITY_EDITOR
- void OnValidate()
- {
- if (autoUpdateInEditor)
- {
- if (background == null)
- {
- background = GetComponent<RectTransform>();
- }
- Resize();
- }
- }
- #endif
- public void Resize()
- {
- if (text == null || background == null || maxWidth <= 0)
- return;
- // 1. Definiamo la larghezza massima del testo.
- // Questa è la larghezza massima dello sfondo meno il DOPPIO del padding orizzontale (sinistra + destra).
- float maxTextWidth = maxWidth - (padding.x * 2);
- // 2. Calcoliamo la dimensione preferita del testo con il vincolo di larghezza.
- Vector2 preferredSize = text.GetPreferredValues(text.text, maxTextWidth, float.PositiveInfinity);
- // 3. La nuova dimensione dello sfondo sarà la dimensione del testo
- // più il DOPPIO del padding (sinistra+destra e sopra+sotto).
- Vector2 backgroundSize = new Vector2(preferredSize.x + (padding.x * 2), preferredSize.y + (padding.y * 2));
- // Applica la dimensione calcolata al RectTransform del background.
- background.sizeDelta = backgroundSize;
- LayoutRebuilder.ForceRebuildLayoutImmediate(background);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment