Resize font of all texts to the same value
I have some Text objects in UI. And I set Best Fit to true for all of them.the problem that I face,is that the length of their texts are variable,therefore their responsive font sizes are different from each other. I tried to write this script to change the font size of all texts to the smallest one but it wont work. How can I overcome this problem?
public class FontResizer : MonoBehaviour {
public Text[] txtBoxes;
public float[] fontSizes;
float min;
void Start () {
fontSizes = new float[txtBoxes.Length];
for (int i = 0; i < fontSizes.Length; i++)
{
fontSizes[i] = txtBoxes[i].cachedTextGenerator.fontSizeUsedForBestFit;
}
min = 100000;
for (int i = 0; i < fontSizes.Length; i++)
{
if (min > fontSizes[i])
{
min = fontSizes[i];
}
}
for (int i = 0; i < fontSizes.Length; i++)
{
txtBoxes[i].resizeTextForBestFit = false;
}
for (int i = 0; i < fontSizes.Length; i++)
{
txtBoxes[i].fontSize = Mathf.FloorToInt(min);
}
}
}
Not sure if you ran into this issue as well, but do you know of a way to run code whenever Best Fit resizes the text? I basically want to run this code to sync the font sizes every time the size changes, but I can't seem to find any event for it.
Answer by Mike-Geig · Aug 24, 2016 at 08:31 PM
You need to delay a single frame size the "best fit" size is still being determined in Frame 1. Therefore, putting the code in a coroutine will help. I also cleaned it up a little
public Text[] txtBoxes;
void Start ()
{
StartCoroutine (SetTextSize ());
}
IEnumerator SetTextSize ()
{
//Need to delay a frame
yield return null;
int minSize = 1000;
//Find smallest
for (int i = 0; i < txtBoxes.Length; i++)
{
if (minSize > txtBoxes [i].cachedTextGenerator.fontSizeUsedForBestFit)
minSize = txtBoxes [i].cachedTextGenerator.fontSizeUsedForBestFit;
}
//Set smallest
for (int i = 0; i < txtBoxes.Length; i++)
{
txtBoxes[i].resizeTextMaxSize = minSize;
}
}
Your answer
Follow this Question
Related Questions
Canvas Text Help 0 Answers
Font looks very bad (not blurry) 0 Answers
how to get dice number in ui text 2 Answers
How To Load TTF Font From External File 0 Answers
CharacterInfo.glyphWidth always 0 2 Answers