0
\$\begingroup\$

I am using Unity 2021.3.3f1 and trying to make a pop up with a sprite as a background, where the size of this sprite adjusts to the size necessary to fit the text.

From what I understand, UnityEngine.UI.TextGenerator should be able to give me the necessary dimensions of the sprite, given an input string and some TextGenerationSettings.

Here is the code I am using.

public class PopUp : MonoBehaviour
{
    UnityEngine.UI.Text text;
    TextGenerationSettings textGenSetting;
    TextGenerator generator


    void Start()
    {
        generator = new TextGenerator();
        textGenSetting.generationExtents = new Vector2(20f, 20f);
    }

    void Update()
    {
        RecalculateText();
    }

    private void RecalculateText()
    {
        textGenSetting.fontSize = text.fontSize;
        textGenSetting.alignByGeometry = text.alignByGeometry;
        textGenSetting.color = text.color;
        textGenSetting.fontStyle = text.fontStyle;
        textGenSetting.resizeTextForBestFit = text.resizeTextForBestFit;
        textGenSetting.resizeTextMaxSize = text.resizeTextMaxSize;
        textGenSetting.resizeTextMinSize = text.resizeTextMinSize;
        textGenSetting.richText = text.supportRichText;
        textGenSetting.horizontalOverflow = text.horizontalOverflow;
        textGenSetting.verticalOverflow = text.verticalOverflow;
        textGenSetting.updateBounds = true;
        textGenSetting.font = text.font;
        textGenSetting.lineSpacing = text.lineSpacing;
        
 
        var newHeight = generator.GetPreferredHeight(text.text, textGenSetting);
        var newWidth = generator.GetPreferredWidth(text.text, textGenSetting);
        var newRect = generator.rectExtents;

        //Debug Log 1
        Debug.Log(string.Format("newWidth: {0}, newHeight: {1}, numLinesGenerated: {2}", newWidth, newHeight, generator.lineCount));
        
        //Debug Log 2
        Debug.Log(string.Format("newRectWidth: {0}, newRectHeight: {1}, numLinesGenerated: {2}", newRect.width, newRect.height, generator.lineCount));
        
        //Debug Log 3
        Debug.Log(string.Format("generationExtents: width {0}, height: {1}, numLinesGenerated: {2}", textGenSetting.generationExtents.x, textGenSetting.generationExtents.y, generator.lineCount));
    }
}

Since I'm not sure which method/field should be giving me the correct height and width for any given text, I'm printing multiple fields/method results to the console.

However, none of those gives the desired result.


Outputs of Debug Log 1

The line marked //Debug Log 1 above gives the following output when I have an empty string (""), a string with one character ("a"), a string with two characters ("aa"), and a long string (with plenty of spaces in between for potential line breaks)

Text is : . newWidth: 0, newHeight: 15, numLinesGenerated: 1

Text is : a. newWidth: 7, newHeight: 30, numLinesGenerated: 1

Text is : aa. newWidth: 14, newHeight: 45, numLinesGenerated: 1

Text is : Nam a tempor lorem. Ut eleifend, massa sed tincidunt blandit, risus nunc pharetra orci, at mattis turpis augue eu eros. Aliquam a faucibus dolor. Vestibulum ultrices turpis quis mi aliquam, a facilisis metus rutrum. Nulla sodales, ante vitae maximus fringilla, tellus erat ultricies felis, ac sodales felis lorem nec lorem. Fusce cursus turpis odio, vel tristique justo pulvinar sed. Nunc efficitur, ante ac mollis pretium, elit felis elementum lorem, vitae porttitor ex arcu vulputate ante. Donec elit purus, porta nec tortor vitae, semper suscipit sem. Ut ante dui, lobortis vel nulla vitae, condimentum laoreet magna. Maecenas aliquet aliquet nulla a fringilla. Proin rhoncus est eget nunc venenatis tempus. Praesent rhoncus est et velit gravida, non posuere justo scelerisque. Praesent ultrices lectus quis quam iaculis faucibus quis id sem. Quisque enim massa, molestie ac tortor sit amet, porta tristique diam. Suspendisse potenti. Fusce rutrum massa metus, eu facilisis nisi luctus vel.. newWidth: 5634, newHeight: 12675, numLinesGenerated: 1

Outputs of Debug Log 2

Here's the same for //Debug Log 2

Text is: . newRectWidth: 0, newRectHeight: 15, numLinesGenerated: 1

Text is: a. newRectWidth: 7, newRectHeight: 15, numLinesGenerated: 1

Text is: aa. newRectWidth: 14, newRectHeight: 15, numLinesGenerated: 1

Text is: Nam a tempor lorem. Ut eleifend, massa sed tincidunt blandit, risus nunc pharetra orci, at mattis turpis augue eu eros. Aliquam a faucibus dolor. Vestibulum ultrices turpis quis mi aliquam, a facilisis metus rutrum. Nulla sodales, ante vitae maximus fringilla, tellus erat ultricies felis, ac sodales felis lorem nec lorem. Fusce cursus turpis odio, vel tristique justo pulvinar sed. Nunc efficitur, ante ac mollis pretium, elit felis elementum lorem, vitae porttitor ex arcu vulputate ante. Donec elit purus, porta nec tortor vitae, semper suscipit sem. Ut ante dui, lobortis vel nulla vitae, condimentum laoreet magna. Maecenas aliquet aliquet nulla a fringilla. Proin rhoncus est eget nunc venenatis tempus. Praesent rhoncus est et velit gravida, non posuere justo scelerisque. Praesent ultrices lectus quis quam iaculis faucibus quis id sem. Quisque enim massa, molestie ac tortor sit amet, porta tristique diam. Suspendisse potenti. Fusce rutrum massa metus, eu facilisis nisi luctus vel.. newRectWidth: 5634, newRectHeight: 15, numLinesGenerated: 1

Outputs of Debug Log 3

And here for Debug Log 3

Text is: . generationExtents: width 20, height: 20, numLinesGenerated: 1

Text is: a. generationExtents: width 20, height: 20, numLinesGenerated: 1

Text is: aa. generationExtents: width 20, height: 20, numLinesGenerated: 1

Text is: Nam a tempor lorem. Ut eleifend, massa sed tincidunt blandit, risus nunc pharetra orci, at mattis turpis augue eu eros. Aliquam a faucibus dolor. Vestibulum ultrices turpis quis mi aliquam, a facilisis metus rutrum. Nulla sodales, ante vitae maximus fringilla, tellus erat ultricies felis, ac sodales felis lorem nec lorem. Fusce cursus turpis odio, vel tristique justo pulvinar sed. Nunc efficitur, ante ac mollis pretium, elit felis elementum lorem, vitae porttitor ex arcu vulputate ante. Donec elit purus, porta nec tortor vitae, semper suscipit sem. Ut ante dui, lobortis vel nulla vitae, condimentum laoreet magna. Maecenas aliquet aliquet nulla a fringilla. Proin rhoncus est eget nunc venenatis tempus. Praesent rhoncus est et velit gravida, non posuere justo scelerisque. Praesent ultrices lectus quis quam iaculis faucibus quis id sem. Quisque enim massa, molestie ac tortor sit amet, porta tristique diam. Suspendisse potenti. Fusce rutrum massa metus, eu facilisis nisi luctus vel.. generationExtents: width 20, height: 20, numLinesGenerated: 1

Conclusion

Debug Log 1

generator.GetPreferredWidth adds 7 to the preferred width for each character (and 4 for each space) and generator.GetPreferredHeight adds 15 to the preferred height for each character (no idea why) and neither GetPreferredWidth nor GetPreferredHeight calculate line Breaks in any sensible way

Debug Log 2

generator.rectExtents.width gets incremente by 7 for each character (and 4 for each space), but generator.rectExtents.height is not incremented at all (so again, no line breaks or valid height readings)

Debug Log 3

This (probably expected) always outputs 20,20 (i.e., whatever textGenSetting.generationExtents is set to). I tried this anyway since I thought maybe generator.Populate() would update this value of the textGenSetting struct.

Question: Am I missing something? Or is this in some way expected behaviour? How can I get this to work, or, alternatively, use some other way to auto-layout text and get the extents of said text so that I can adjust my sprites to fit this text?

Here are my text settings, for complete information.

enter image description here

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Welp, turns out after writing this post, even though I had done quite some research before, I finally found an answer. Changing my RecalculateText method to the following worked, allthough I haven't investigated where I went wrong with my previous approaches.

private void RecalculateText(string sText)
    {
        TextGenerator textGen = new TextGenerator();
        TextGenerationSettings tgSettings = text.GetGenerationSettings(text.rectTransform.rect.size);
        var width = textGen.GetPreferredWidth(text.text, tgSettings);
        var height = textGen.GetPreferredHeight(text.text, tgSettings);
    }

Kudos go to pineda100 over on the unity forum, who's answer to a similar question provided the snippet above.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .