using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; public class BestfitText : Text { #region public int VerticalMinSize = 1; public int VerticalMaxSize = 29; protected string FormerText; #endregion protected void Update() { } protected override void OnPopulateMesh(VertexHelper toFill) { base.OnPopulateMesh(toFill); if (text != FormerText) { FormerText = text; StartCoroutine(DelayCall(Bestfit, 1)); } } protected void Bestfit() { TextGenerationSettings textGenerationSettings = GetGenerationSettings(rectTransform.rect.size); bool shrink = false; bool expand = false; int antiCrush = 0; while (true) { antiCrush++; if (antiCrush > 1000) { Debug.LogError("Crush"); break; } float bestHeight = cachedTextGenerator.GetPreferredHeight(text, textGenerationSettings); if (bestHeight > rectTransform.rect.size.y*canvas.scaleFactor) { textGenerationSettings.fontSize--; if (textGenerationSettings.fontSize < VerticalMinSize) { textGenerationSettings.fontSize = VerticalMinSize; break; } else if (textGenerationSettings.fontSize > VerticalMaxSize) { textGenerationSettings.fontSize = VerticalMaxSize; } else { if (expand) { break; } else { shrink = true; } } } else if (bestHeight < rectTransform.rect.size.y * canvas.scaleFactor) { if (shrink) { break; } textGenerationSettings.fontSize++; if (textGenerationSettings.fontSize < VerticalMinSize) { textGenerationSettings.fontSize = VerticalMinSize; } else if (textGenerationSettings.fontSize >= VerticalMaxSize) { textGenerationSettings.fontSize = VerticalMaxSize; break; } else { expand = true; } } else if (bestHeight.Equal(rectTransform.rect.size.y * canvas.scaleFactor)) { break; } } fontSize = textGenerationSettings.fontSize; } protected IEnumerator DelayCall(UnityAction unityAction, int frame) { while (frame-- > 0) { yield return null; } unityAction.SafeInvoke(); } }