[UI] "Best fit" in text object stretches a single word across two lines

Here are the settings of my text object and how it looks like in the editor:

I’m using a custom font and have “Best fit” enabled with a big enough min-max to allow for essentially any amount of resizing. However, when I enter play mode, this happens:


As you can see, the word was cut in two parts and rendered in different lines.

Q: How can I prevent Unity from doing this without turning off “Best fit”?

I think there’s no simple way to tell Unity not to do that, but there should be a checkbox when turning on “Best fit” with wrap and truncate to tell it to not cut words.

Anyway, I guess you can fix that with a script. I haven’t tried this, but I guess it should work as long as you want a single line.

  1. Get the font size selected by Unity to do the best fit.
  2. Get the height of the text component.
  3. If the height is at least twice the font size, shrink the component to the fontSize value.
  4. That should force Unity to shrink the font again.

I did a quick script that seems to work, but I haven’t tested it a lot. You have to use an anchoring setting in your text that allows you to change the height of the component (so sizeDelta.y is the height).

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class BestFitWithoutCutting : MonoBehaviour {

	public Text text;

	void Start () {
		StartCoroutine (FixHeight ());
	IEnumerator FixHeight() {
		yield return null;

		TextGenerator gen = text.cachedTextGenerator;
		Rect rect = text.rectTransform.rect;

		while (rect.height >= 2*gen.fontSizeUsedForBestFit) {
			text.rectTransform.sizeDelta = new Vector2(text.rectTransform.sizeDelta.x,gen.fontSizeUsedForBestFit);
			yield return null;
			rect = text.rectTransform.rect;

There is actually a very simple way to force your text into a single line.

Increase the parameter “Line Spacing” to an impractical value such as 100 or 1000.

As there would not be enough space for the text to occupy more than one line with that much Line Spacing, your text would always be a single line.

Best fit simply fills all available space with font, with respects to max and min size.

If you don’t want it overflowing into two rows, simply shrink the text field a bit.

I see you are using a button. Within that button there is a text field which fills it up. Make the text field not as wide, and make sure to position the anchors on the edges of the text field (not entire button!).

If your text field isn’t high enough for two rows, only one row will be displayed - simple as that.