ぱふの自由帳

週3更新(火・木・日)を目指すUnityブログ。良ければフォローお願いします(`・ω・´)

Textを1文字ずつ表示する(旧版:TextMeshPro未使用)

はじめに

今回は以下のような機能を作成していきたいと思います。

f:id:PafuOfDuck:20170614093000g:plain

実装

以下のような機能を持たせるようにします。

  • 1文字ずつ表示を行う
  • 表示途中でキーが押されたら残りの文章を一気に表示
  • 表示完了時にキーが押されたら次の文章へ

UIを設置する

UIの設置は特に解説しないので、UIの設置方法が分からない方はGoogle先生に聞いてください。

TextController.csを作成

先ほど挙げた機能を持たせるためにスクリプトに記述していきます。いつもお世話になっているテラシュールブログさんの以下の記事を参考にしています。(ほとんど真似していますが...)

tsubakit1.hateblo.jp

TextController.cs

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

public class TextController : MonoBehaviour {

    public string[] sentences; // 文章を格納する
    [SerializeField] Text uiText;   // uiTextへの参照

    [SerializeField][Range(0.001f, 0.3f)]
    float intervalForCharDisplay = 0.05f;   // 1文字の表示にかける時間

    private int currentSentenceNum = 0; //現在表示している文章番号
    private string currentSentence = string.Empty;  // 現在の文字列
    private float timeUntilDisplay = 0;     // 表示にかかる時間
    private float timeBeganDisplay = 1;         // 文字列の表示を開始した時間
    private int lastUpdateCharCount = -1;       // 表示中の文字数


    void Start () {
        SetNextSentence ();
    }
    

    void Update () {
        // 文章の表示完了 / 未完了
        if (IsDisplayComplete ()) {
            //最後の文章ではない & ボタンが押された
            if (currentSentenceNum < sentences.Length && Input.GetKeyUp (KeyCode.Space)) {
                SetNextSentence ();
            }
        } else {
            //ボタンが押された
            if (Input.GetKeyUp (KeyCode.Space)) {
                timeUntilDisplay = 0; //※1
            }
        }

        //表示される文字数を計算
        int displayCharCount = (int)(Mathf.Clamp01((Time.time - timeBeganDisplay) / timeUntilDisplay) * currentSentence.Length);
        //表示される文字数が表示している文字数と違う
        if (displayCharCount != lastUpdateCharCount) {
            uiText.text = currentSentence.Substring (0, displayCharCount);
            //表示している文字数の更新
            lastUpdateCharCount = displayCharCount;
        }
    }

    // 次の文章をセットする
    void SetNextSentence(){
        currentSentence = sentences [currentSentenceNum];
        timeUntilDisplay = currentSentence.Length * intervalForCharDisplay;
        timeBeganDisplay = Time.time;
        currentSentenceNum++;
        lastUpdateCharCount = 0;
    }

    bool IsDisplayComplete(){
        return Time.time > timeBeganDisplay + timeUntilDisplay; //※2
    }
}

※1...0にするとMathf.Clamp01()で強制的に1になるようにしています
※2...終了しているかを時間で確認しています

TextControllerオブジェクト作成 -> 設定

空のゲームオブジェクト作成して、名前をTextControllerにします。
次にTextControllerにTextController.csをアタッチします。 アタッチできたら、以下のように設定します。

f:id:PafuOfDuck:20170614094940p:plain

  • Interval For Char Dispというのは1文字の表示にかける時間なので適当に設定してください。
  • Ui Textには各自作成したUIのTextを設定してください。

完成

再生すると動くと思います。

おわりに

以上です。新たに追加機能が必要になれば随時更新していきたいと思いますー。

初心者の方や熟練者の方を問わずTwitterのフォローお待ちしています...(`・ω・´) ヨロシク!