Created
September 2, 2025 10:10
-
-
Save sonnguyen9800/5024763082c3170069ffc1c4b097dda4 to your computer and use it in GitHub Desktop.
[Unity] Auto height increase based on number of lineCount in TMP_Text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
using TMPro; | |
#if UNITY_EDITOR | |
using UnityEditor; | |
#endif | |
namespace Game | |
{ | |
[ExecuteAlways] // Allow execution in Editor and Play mode | |
public class UIDialogTutorial : MonoBehaviour | |
{ | |
[SerializeField] private RectTransform rectTransform; | |
[SerializeField] private TMP_Text textContent; | |
[Header("Dialog Settings")] | |
[SerializeField] private float minUIHeight = 210f; | |
/// <summary> | |
/// Resizes dialog height based on text content | |
/// </summary> | |
private byte currentLineCountAtMinHeight = 2; | |
public void SetupHeight() | |
{ | |
if (textContent == null || rectTransform == null) return; | |
textContent.ForceMeshUpdate(); | |
Canvas.ForceUpdateCanvases(); | |
// Now preferredHeight is valid | |
float preferredHeight = textContent.GetPreferredValues(textContent.text, textContent.rectTransform.rect.width, 0).y; | |
int lineCount = textContent.textInfo.lineCount; | |
float heightExtraPerLine = preferredHeight / lineCount; | |
// Convert to line count | |
float newHeight = Mathf.Max(minUIHeight, minUIHeight + (lineCount - currentLineCountAtMinHeight) * heightExtraPerLine); | |
rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, newHeight); | |
} | |
#if UNITY_EDITOR | |
// Automatically update in editor when something changes (to help debugging) | |
private void OnValidate() | |
{ | |
Debug.Log("OnValidate"); | |
// Delay to next frame so TMP updates first | |
EditorApplication.delayCall += () => | |
{ | |
if (this != null) SetupHeight(); | |
}; | |
} | |
#endif | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment