Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
3
Question by HarryE22 · Feb 06, 2015 at 01:12 PM · uitextoverflow

Detect Text Box Overflow

I have a text box that is filled with text from an XML. Sometimes there is so much text that it goes beyond the boundaries of the text box. I can't use best fit because the font size needs to remain consistent for design purposes.

Is there a way I can query the text box to find out if the text inside is going beyond the boundaries of the RectTransform?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
4
Wiki

Answer by hubatish · Jun 03, 2015 at 05:25 AM

I had roughly this problem recently with Unity 4.6 UI; hopefully you've already solved yours or work-arounded it, but to answer the question:

     private Text text;
     private RectTransform parentRect;
     [SerializeField]
     private float longestCharWidth = 50;
 
     protected void Start()
     {
         parentRect = GetComponent<RectTransform>();
         InputField inputField = gameObject.GetComponent<InputField>();
         text = inputField.textComponent;
     }

     //Return whether the text is too wide for the current field.  
     protected bool CheckTextWidth()
     {
         float textWidth = LayoutUtility.GetPreferredWidth(text.rectTransform); //This is the width the text would LIKE to be
         float parentWidth = parentRect.rect.width; //This is the actual width of the text's parent container
         return (textWidth > (parentWidth-longestCharWidth)); //is the text almost too wide?  Stop when the next character could be too wide
     }
 

Specifically, my use case was to make sure a user couldn't type a too long entry into an InputField. Since the InputField would scroll over/resize once it overflowed, I had to subtract the longestCharWidth.

The main part of my answer comes from: http://answers.unity3d.com/questions/836642/new-ui-46-how-to-show-ellipsis-for-text-overflow.html

And here's my full solution (to making sure a user couldn't enter too much info)

     public char ValidateInput(string text, int charIndex, char addedChar)
     {
         if(CheckTextWidth())
         {
             return '\0';
         }
         else
         {
             return addedChar; 
         }
     }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Leggy7 · Aug 31, 2016 at 07:41 PM 0
Share

That's actually pretty nice. I struggled to find a solution for this problem and just badly workarounded it. Now with this comparison, in my use case - where I need to fit a string inside a Text -, I can easily decrease the font size within a loop until it fits. Thanks a lot

avatar image
1

Answer by gjf · Feb 06, 2015 at 12:57 PM

look at TextGenerator and all the fun stuff with it... you can get the length of what would be rendered then compare with your dimensions

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by CaptainNoah · Sep 29, 2020 at 06:40 PM

In case anyone else lands here looking for help with this, I wrote an extension to the Text class. I haven't tested the one for width yet but the verticle test definitely works

 using UnityEngine;
 using UnityEngine.UI;
 
 public static class TextExtension
 {
     /// <summary>
     /// Returns true when the Text object contains more lines of text than will fit in the text container vertically
     /// </summary>
     /// <returns></returns>
     public static bool IsOverflowingVerticle(this Text text)
     {
         return LayoutUtility.GetPreferredHeight(text.rectTransform) > GetCalculatedPermissibleHeight(text);
     }
 
     private static float GetCalculatedPermissibleHeight(Text text)
     {
         if (cachedCalculatedPermissibleHeight != -1) return cachedCalculatedPermissibleHeight;
 
         cachedCalculatedPermissibleHeight = text.gameObject.GetComponent<RectTransform>().rect.height;
         return cachedCalculatedPermissibleHeight;
     }
     private static float cachedCalculatedPermissibleHeight = -1;
 
     /// <summary>
     /// Returns true when the Text object contains more character than will fit in the text container horizontally
     /// </summary>
     /// <returns></returns>
     public static bool IsOverflowingHorizontal(this Text text)
     {
         return LayoutUtility.GetPreferredWidth(text.rectTransform) > GetCalculatedPermissibleHeight(text);
     }
 
     private static float GetCalculatedPermissibleWidth(Text text)
     {
         if (cachedCalculatedPermissiblWidth != -1) return cachedCalculatedPermissiblWidth;
 
         cachedCalculatedPermissiblWidth = text.gameObject.GetComponent<RectTransform>().rect.width;
         return cachedCalculatedPermissiblWidth;
     }
     private static float cachedCalculatedPermissiblWidth = -1;
 
 }

If you aren't familiar with using extensions, you create a TextExtension script in your project, then you can call this from any other script like it is built-in Text method.

 // set in inspector
 public Text myText;
 
 private void Update()
 {
    print("text is overflowing? " + myText.IsOverflowingVerticle();
 }

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Right approach to prompt a Dialog Box asking for text (equivalent to AlertDialog.Builder and EditText in Android Studio) 0 Answers

Unity UI Text - Always show 5 last lines 0 Answers

Changing the UI text value from server to Client side 0 Answers

Text smaller on higher resolution screen than on lower resolution screen 1 Answer

How would i go about having a UI text element that becomes larger and smaller based on how close or far the player is? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges