9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Unity C# でアドベンチャー風テキスト作成

Last updated at Posted at 2019-09-07

今日は趣味の方の投稿です。
やりたかったのは以下のこと。

  • テキストをtextコンポーネントに表示
  • 全てを表示し終わったらアニメーターのついたイメージを表示
  • クリック(タッチ)したら文章をスキップする

↓完成図

##実際のコード
https://qiita.com/ryouhei_de/items/74bf63d35f28594b78a4
こちらの記事を参考にさせていただきつつ、
スキップ機能をつけてみました。

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

public class textbox : MonoBehaviour
{
    [SerializeField] List<string> messageList = new List<string>();//会話文リスト
    [SerializeField] float novelSpeed;//一文字一文字の表示する速さ
    int novelListIndex = 0; //現在表示中の会話文の配列
    Text textArea;
    public GameObject TextTouch; //文を出し切ったら表示する
    bool isSkipFlag = false; //スキップ可能かどうか
    int messageCount = 0; //現在表示の文字数

    // Start is called before the first frame update
    void Start()
    {
        this.textArea = GetComponent<Text>();
        StartCoroutine(Novel());
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.anyKeyDown && isSkipFlag){
            this.textArea.text = messageList[novelListIndex];
            messageCount = messageList[novelListIndex].Length;
        }
    }

    private IEnumerator Novel()
    {
        this.textArea.text= ""; //テキストのリセット
        
        while (messageList[novelListIndex].Length > messageCount)//文字をすべて表示していない場合ループ
        {
            isSkipFlag = true;
            
            this.textArea.text += messageList[novelListIndex][messageCount];//一文字追加
            messageCount++;//現在の文字数
            yield return new WaitForSeconds(novelSpeed);//任意の時間待つ
        }

        novelListIndex++; //次の会話文配列
        isSkipFlag = false;
        TextTouch.SetActive(true);
        yield return new WaitUntil(Touch);
        TextTouch.SetActive(false);
        messageCount = 0;
        if (novelListIndex < messageList.Count)//全ての会話を表示していない場合
        {
            StartCoroutine(Novel());
        }
    }
    bool Touch(){
        return Input.anyKeyDown;
    }
}

参考サイトの通り、コルーチンで字が出るまでの待機・クリックするまでの待機を行なっています。
ちょっと異なるのが、updateでクリックされた場合に字を強制的に全て
表示させるとこですね。
その為にmessageCountをwhileループから出したので、
その辺の処理がチョコチョコ入った感じです。

textTouchというのはテキストボックスの最後に表示される「touch」を促すアニメーションのコンポーネントです。

c#まだまだ慣れないですけど書きやすくていいですね。

9
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?