0
\$\begingroup\$

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);
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ Even if the text adds 3 letters every time, this code works smoothly on my computer. \$\endgroup\$
    – lvictorino
    Mar 11, 2017 at 6:22
  • \$\begingroup\$ @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. \$\endgroup\$
    – Gnemlock
    Mar 11, 2017 at 15:52
  • \$\begingroup\$ You might also find this thread useful, which is about using a fading transition letter-by-letter. \$\endgroup\$
    – DMGregory
    Mar 11, 2017 at 17:21

1 Answer 1

3
\$\begingroup\$

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;
        textDisplayed = textToType.Substring(0, (int)numOfCharsSoFar);  
    }

    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)

hamster typing

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .