【Unity】テキストを一文字ずつ表示させるシンプル実装(タイプライター風?+スキップ対応)

Unity

1文字ずつ文字送りをするログ表示ってよくあると思います。
今回作っているゲームでも使ってみたいなーと思ったのでざっくり実装してみました。

大したものではないですが、サンプルとしてシンプル実装を備忘録として残しておきたいと思います。

対象のテキストをアタッチして実行したら文字送りが開始。
スペースキーでスキップされます。(この辺はよしなに…)

using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class TypewriterEffect : MonoBehaviour
{
    [SerializeField] TextMeshProUGUI textUI;
    [TextArea] [SerializeField] private string fullText;
    [SerializeField] float delay = 0.05f;
    [SerializeField] KeyCode skipKey = KeyCode.Space;

    Coroutine typingCoroutine;
    bool isSkipping = false;

    void Start()
    {
        typingCoroutine = StartCoroutine(ShowText());
    }

    IEnumerator ShowText()
    {
        textUI.text = "";

        foreach (char c in fullText)
        {
            if (isSkipping)
            {
                textUI.text = fullText;
                yield break;
            }

            textUI.text += c;
            yield return new WaitForSeconds(delay);
        }
    }

    void Update()
    {
        if (Input.GetKeyDown(skipKey))
        {
            isSkipping = true;

            if (typingCoroutine != null)
            {
                StopCoroutine(typingCoroutine);
                textUI.text = fullText;
            }
        }
    }
}

特に説明するものないくらいシンプルなものですが、どなたかの役に立てば幸いです。

コメント

タイトルとURLをコピーしました