Determining best font size in script

In my game the narrator pops up in various places and “speaks to you” via text in a speech bubble… meaning that the characters appear one at a time. To make the experience better, I’m attempting to programmatically calculate the best font size to use based on the length of the text string that will be displayed. Here’s where things stand at the moment:

textGenSettings = dialogNarratorText.GetGenerationSettings(dialogNarratorText.rectTransform().rect.size);
textGenSettings.verticalOverflow = VerticalWrapMode.Truncate; //Set this manually since it's actually "Overflow" in the editor since otherwise the fontSize returned sometimes causes the last line to just *barely* get cropped off
textGenSettings.resizeTextMinSize = 6;
textGenSettings.resizeTextMaxSize = 160;
textGenSettings.resizeTextForBestFit = true;
textGenSettings.scaleFactor = 1f; //For some reason, everything is wrong without this...

dialogNarratorText.cachedTextGenerator.Populate(dialogText, textGenSettings);

//Get and set font size
int fontSize = dialogNarratorText.cachedTextGenerator.fontSizeUsedForBestFit - 2; //-2 here since at 0 or -1 it ends up being slightly too big and the last line gets wrapped on some devices...
dialogNarratorText.fontSize = fontSize;
textGenSettings.resizeTextForBestFit = false;
textGenSettings.fontSize = fontSize;

//Set the real size
float preferredHeight = dialogNarratorText.cachedTextGenerator.GetPreferredHeight(dialogText, textGenSettings);
float actualHeight = preferredHeight;

dialogNarratorText.rectTransform().sizeDelta = new Vector2(dialogNarratorText.rectTransform().sizeDelta.x, actualHeight);

The call to dialogNarratorText.cachedTextGenerator.Populate is really slow which causes an obvious hiccup in frame rate. There must be a way better way of doing this… but I haven’t done anything like this in Unity before so I’m currently stuck. I also don’t currently use TextMesh Pro, but recognize that may be the answer somehow.

Ideas? Thanks for the help!

You may find TextMeshPro is very helpful here (it’s free now):

As a side note, I highly recommend you use TextMeshPro for any new projects, it’s just so superior vs the Unity Text objects.

1 Like

wow yeah… that’s fantastic. Looks like I have my next project…

Thanks so much for the video!

1 Like