UI Text: Words at end of line jumping to next line
I was coding a dialogue system with autotyping, I made a coroutine and just noticed the words at the end of a line jumped to next line. So in case someone else is wondering how to fix this issue, here is my solution.
     private IEnumerator AutoType (Text textUI, string text) {
         yield return null;
         textUI.text = text;
         Canvas.ForceUpdateCanvases();
         textUI.text = string.Empty;
 
         text = GetFormattedText(textUI, text);
         for (int i = 0; i < text.Length; i++) {
             textUI.text = text.Substring(0, i + 1);
             yield return new WaitForSeconds(0.025f);
         }
     }
 
     private string GetFormattedText (Text textUI, string text) {
         string[] words = text.Split(' ');
 
         int width = Mathf.FloorToInt(textUI.rectTransform.sizeDelta.x);
         int space = GetWordSize(" ", textUI.font, textUI.fontSize);
 
         string newText = string.Empty;
         int count = 0;
         for (int i = 0; i < words.Length; i++) {
             int size = GetWordSize(words[i], textUI.font, textUI.fontSize);
 
             if (i == 0) {
                 newText += words[i];
                 count += size;
             }
             else if (count + space > width || count + space + size > width) {
                 newText += "\n";
                 newText += words[i];
                 count = size;
             }
             else if (count + space + size <= width) {
                 newText += " " + words[i];
                 count += space + size;
             }
         }
         return newText;
     }
 
     private int GetWordSize (string word, Font font, int fontSize) {
         char[] arr = word.ToCharArray();
         CharacterInfo info;
         int size = 0;
         for (int i = 0; i < arr.Length; i++) {
             font.GetCharacterInfo(arr[i], out info, fontSize);
             size += info.advance;
         }
         return size;
     }
 
               So basically I get the width of each word and the I check if it fits inside the RectTransform.
               Comment
              
 
               
              Your answer
 
             Follow this Question
Related Questions
How to get access to other's script var with increment? 0 Answers
UI Text created from C# Script 0 Answers
[HELP] To show wave number on a zombie survival game. 0 Answers
Changing the UI Text 0 Answers
ui Text not responding to collider 1 Answer