I am making a game with animated dialogue and I run into a problem when one word is being written in one line and then when it takes too much space it jumps down to the next line. I demonstrated that in this video (I slowed down text writing so it’s obvious what is happening). You can see the word “possible” being written in one line, and then finished down on next line.
Does anyone have any idea how we could predict that word is going to be too long for that line, and then start writing it in next line right away? I had idea of testing how long the next word is going to be, by checking how many characters there are until the next Space in string. But even if I do this, I don’t know how to test if that word is going to be too long to fit in current line or will it be pushed into the next line.
Here is simplified version of function that I run in Update() to animate text:
if (currentlyAnimatedText.Length > 0)
char letter = char.Parse(currentlyAnimatedText.Substring(0, 1));
currentlyUsedDialogueBox.text += letter;
currentlyAnimatedText = currentlyAnimatedText.Remove(0, 1);
I ended up solving this by instead of writing char by char, I wrote whole dialogue text but then changed color of the text to alpha 0. And then instead of adding char’s I just moved this tag “”) thought the text, making it look like it’s writing text, even thought whole text is already there.
Here is the simplified code:
string currentlyAnimatedText = "";//assign dialogue text here
string tempAnimatedText = "";
if (currentlyAnimatedIndex < currentlyAnimatedText.Length)
currentlyUsedDialogueBox.text = currentlyAnimatedText;
tempAnimatedText = currentlyUsedDialogueBox.text.Insert(currentlyAnimatedIndex, "<color=#00000000>");
currentlyUsedDialogueBox.text = tempAnimatedText;
You’ll need to figure out how best to incorporate this into your dialog system, but as a start you can determine the width required to display a string as follows:
var text = GetComponent<Text>();
var textGenerator = text.cachedTextGenerator;
var textSettings = text.GetGenerationSettings(Vector2.zero);
string dialog = "Hello, world!";
float width = textGenerator.GetPreferredWidth(dialog, textSettings);
Debug.Log("width needed: " + width);