Prevent Text too long and trim empty space

Is there a simple way to limit the number of characters a user can input in the TextField in Unity? and also trim the empty spaces before the first character and after the last character. I tried to research online. The solutions were all very long and hard to comprehend.

In addition, is there a simple way to limit the number of lines being shown? (like IOS Xcode Swift: .numberOfLines = 1)

2 Likes

You can adjust the number of lines being shown with the maxVisibleLines property on the TMP_Text component.

Removing trailing or leading spaces is very easy.

string trimmedString = inputText.text.Trim();

Unfortunately, solutions for restricting the number of characters are complicated, much like your research has indicated. There’s just not an easy way to accomplish this. Essentially, you need to intercept keystrokes on the text, then check the text length and remove any excess characters.

I have a few question about your query:

When you say “a user can input in the TextField in Unity”, do you mean in Editor mode? as in you’re wanting to write some editor code that would allow a Unity user - not a game player - to input some text that would later further down the pipeline become a string in a TextField?

Or are you meaning a player to input some thing like a player name at run time in the game?

Because if you mean the latter, you can easily achieve that by using an InputField, not a TextField, and use the OnValueChange event of that InputField so that with each letter added, you just check the length, check the number of lines, etc

1 Like

Thanks, Solofo. I mean the latter. I will use inputField instead. Thanks!

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms