r/UnityHelp • • Oct 17 '21

PROGRAMMING Question About Sprite Manipulation With Text

Hello Everyone, I am trying to create a gameobject that has a square sprite, the size of the gameobject is depended on 2 factors, one for height and one for width. I've managed to solve the function for height but I still can't manage to produce one for the width. It's function depends on a Text Mesh that is a child of the box. The more the character, the more space. Any idea how i can implement this function?

I have been struggling with problem for quite some time now and i have no clue where to go to solve it.

Thank you very much

3 Upvotes

4 comments sorted by

1

u/Bonejob Code Guru Oct 17 '21

So you want to scale the text based upon the space or the space based upon the text?

Text auto-sizing is designed to scale the text to the defined max point size to fit the text container or RectTransform.

Text Auto-sizing also needs to test various point sizes in order to determine what the optimum point size is for a given text container and as such is not as efficient as just a plain text object with a fixed size.

Given the above, I always recommend users only use Text Auto-sizing to determine the optimum point size for a given text object and then disable this Auto-sizing feature and then manually set the size on all other text objects to this resulting optimum point size. This way you only get the impact of auto-sizing on one object while making sure the point size of all other objects is consistent with the first which does also better UI design / practices.

1

u/Evening-Conference-5 Oct 17 '21

I mean I wondering if it would be possible for gameobject behind the text to be scaled according to how many characters a string has

1

u/Bonejob Code Guru Oct 17 '21

I have never done this I have always scaled the object to the size I need then use the text auto-sizing to put the text in. But you could scale the object to the text if the font size is fixed. It would be something like;

string.length * {integer value};

https://docs.microsoft.com/en-us/dotnet/api/system.string.length?view=net-5.0

The integer value would be the width of a single character plus the kerning of the spacing you want.

1

u/Evening-Conference-5 Oct 18 '21

Well I'm going to be honest I already tried that, but I had problems. The reason is that not every character takes the same amount of space, That would result in the scaling not proportional. That's why I'm having such hard time with this.

I know I can just scale the object than the text but I would rather learn to create features like these so I won't have to compromise.