'Unity: Fast-Forward Type Writer Effect upon Keypress

For the cutscenes of a 2D platformer game, I wrote a script that shows the text like it's written by a typewriter. Since the text can be very long, I want to implement an option for the user to fast-forward/skip the animation and show the full text upon a keypress. This is what I have right now:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TypeWriter : MonoBehaviour
{
    public float delay = 0.05f;
    public string fullText;
    private string currentText = "";

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(ShowText());
    }

    IEnumerator ShowText()
    {
        for (int i = 0; i < fullText.Length + 1; i++)
        {
            currentText = fullText.Substring(0, i);
            this.GetComponent<Text>().text = currentText;
            yield return new WaitForSeconds(delay);
        }
    }
}

Can someone help me please? I'm new to unity as well as C#.



Solution 1:[1]

Setting a flag should do the trick:

    bool skip = false;

    IEnumerator ShowText()
    {
        for (int i = 0; i < fullText.Length + 1; i++)
        {
            currentText = fullText.Substring(0, i);
            this.GetComponent<Text>().text = currentText;
            if (!skip)
              yield return new WaitForSeconds(delay);
        }
    }

Just set skip to true at some point and it will cause the loop to not yield which will result in the loop full completing (a minor optimisation would be to just not loop when the skip flag is set and just fill the text with the remaining letters instead, but I doubt you will have performance issues even with the loop as it's so simple).

You can set the flag to true based on receiving a keypress/some input.

Solution 2:[2]

void Start()
{
    textRef = GetComponent<TextMeshProUGUI>();
    fullText = textRef.text;
    GetComponent<TextMeshProUGUI>().text = "";
    if (typeOnStart)
        StartCoroutine(ShowText(typingDelay));
}
public void StartTyping(float delay)
{
    StartCoroutine(ShowText(typingDelay));
}
IEnumerator ShowText(float delay)
{
    // float time = Time.deltaTime;
    for (int i = 0; i <= fullText.Length; i++)
    {
        // Debug.Log("Typing");
        currentText = fullText.Substring(0, i);
        textRef.text = currentText;
        yield return new WaitForSeconds(typingDelay);
    }
    // float time2 = Time.deltaTime;
    // Debug.Log("Total Time Taken  : " + (time2 - time));
}

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Charleh
Solution 2 Prakyath