Skip to content

Instantly share code, notes, and snippets.

@tomkail
Last active June 14, 2024 10:48
Show Gist options
  • Save tomkail/277b355cb2115fedb159a2387acdb9b6 to your computer and use it in GitHub Desktop.
Save tomkail/277b355cb2115fedb159a2387acdb9b6 to your computer and use it in GitHub Desktop.
Better GetRenderedValues for TextMeshPro that doesn't return NaN/other invalid values and allows you to test with custom text
// Applying float.MaxValue to a rectTransform can cause crashes (not sure why) so we just use a very big number instead.
const float veryLargeNumber = 10000000;
// Gets the tightest bounds for the text by updating the text and using GetRenderedValues
// Note this uses sizeDelta for sizing so won't work when using anchors.
// This is wayyyy more reliable than the actual GetRenderedValues because it won't return stupid values, as GetRenderedValues is prone to doing.
public static Vector2 GetRenderedValues (this TMP_Text textComponent, string text, float maxWidth = veryLargeNumber, float maxHeight = veryLargeNumber, bool onlyVisibleCharacters = true) {
if(string.IsNullOrEmpty(text)) return Vector2.zero;
// Setting RT size to Infinity can lead to weird results, so we use a very large number instead.
if(maxWidth > veryLargeNumber) maxWidth = veryLargeNumber;
if(maxHeight > veryLargeNumber) maxHeight = veryLargeNumber;
var originalRenderMode = textComponent.renderMode;
var originalText = textComponent.text;
var originalSize = textComponent.rectTransform.rect.size;
textComponent.renderMode = TextRenderFlags.DontRender;
textComponent.text = text;
textComponent.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, maxWidth);
textComponent.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, maxHeight);
textComponent.ForceMeshUpdate(true);
// This doesn't work if the component is disabled - but it's better! I'm not even sure this function works while disabled...
// if(textComponent.textInfo.characterCount == 0) return Vector2.zero;
var renderedSize = BetterGetRenderedValues(textComponent, maxWidth, maxHeight, onlyVisibleCharacters);
textComponent.renderMode = originalRenderMode;
textComponent.text = originalText;
textComponent.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, originalSize.x);
textComponent.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, originalSize.y);
textComponent.ForceMeshUpdate(true);
return renderedSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment