# How to make a text box where text “types” smoothly

I want to create a textbox that behaves like most textboxes seen in other games where the text appears gradually. So far this has been my attempt at it but unfortunately, the text appears very unevenly and slow even when changing the letter pause to an insanely low amount.

public float letterPause = 0.1f;

IEnumerator TypeText()
{
//number of char typed per loop
int len = 3;
for (int i = 0; i < text.Length; i += len)
{

if (i + len > text.Length)
{
ibubbletext.text += text.Substring(i, text.Length - i);
}

else
{
ibubbletext.text += text.Substring(i, len);
}
yield return new WaitForSeconds(letterPause);
}
}

• Even if the text adds 3 letters every time, this code works smoothly on my computer. – lvictorino Mar 11 '17 at 6:22
• @Ivictorino, I have to point out that it simply would not look smooth at 3 letters in comparison to 1 letter. That is like saying a 60 fps game looks the same at 20 fps. – Gnemlock Mar 11 '17 at 15:52
• You might also find this thread useful, which is about using a fading transition letter-by-letter. – DMGregory Mar 11 '17 at 17:21

WaitForSeconds isn't accurate enough for this. Here's a better way:

using UnityEngine;

public class TextTyper : MonoBehaviour {

string textToType;
float singleKeyDuration;
string textDisplayed;
float timeStarted;

// Use this for initialization
void Start () {
TypeText("Hello, my name is Lilo Elia.\nYou ate my hamster.\nPrepare to cry!", 6);
}

public void TypeText(string text, float timeToType) {
textToType = text;
var numOfChars = textToType.Length;
singleKeyDuration = timeToType / numOfChars;
textDisplayed = "";
timeStarted = Time.time;
}

void Update () {
var numOfCharsSoFar = (Time.time - timeStarted) / singleKeyDuration;
}

private void OnGUI() {
var style = GUIStyle.none;
style.padding = new RectOffset(10, 10, 10, 10);
style.normal.textColor = Color.black;
GUILayout.Label(textDisplayed,style);
}
}


And the result... :o)

• Of course, the entire OnGUI function there is just for this demo, you don't have to use it in your code. – lilotop Mar 11 '17 at 11:27