Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Text Custom Wrapping

Discussion in 'Getting Started' started by Goodeddie, Aug 26, 2016.

  1. Goodeddie

    Goodeddie

    Joined:
    Aug 3, 2016
    Posts:
    79
    Hello.

    I want to make a dialogue box that types each letter one at a time. So far I can do it except that when it reaches the end of the line, it it will write half of a word and then once it writes the next letter, the word wraps and moves to the next line.

    What kind of logic do I put in so that it knows to move to the second line straight away instead of typing half of the word first?
     
  2. Goodeddie

    Goodeddie

    Joined:
    Aug 3, 2016
    Posts:
    79
    I've attempted to build the logic from scratch.

    How do I figure out how many characters can fit in one line if I am given the width of the Text component?

    string currentLine = "";
    foreach (string word in pages[pageNumber].Split(' '))
    {
    if (word.Length > maxLettersInLine)
    {
    throw new UnityException("Your word is too long!");
    }

    if ((currentLine + word).Length > maxLettersInLine)
    {
    textBox.text += "\n";
    currentLine = string.Empty;
    }

    foreach (char letter in word)
    {
    currentLine += letter;
    textBox.text += letter;
    yield return new WaitForSeconds(secondsBeforeTypingNextLetter);
    }

    currentLine += " ";
    textBox.text += " ";
    }
     
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,848
    Yeah, this is a bit of a hole in the new UI API; there is no good way to get the width of a string.

    But you can get the width of individual characters, using Font.GetCharacterInfo. So you can add these up and figure out where to break your string. See this answer for more details.
     
  4. takatok

    takatok

    Joined:
    Aug 18, 2016
    Posts:
    1,496
    Are you using a UI Text to display your one letter at a time text?
     
  5. Goodeddie

    Goodeddie

    Joined:
    Aug 3, 2016
    Posts:
    79
    Oh nice Font.GetCharacterInfo.