LoginSignup
2
1

More than 3 years have passed since last update.

【Unity】文字列から1文字ずつオブジェクト生成したい("ただいま"→'た','だ','い','ま')

Last updated at Posted at 2019-06-21

経緯

音声認識で取得した文字列から、1文字ずつにして、ばらばらにアニメーションさせたいと思った。

流れとしては

InputField(とりあえず)で、入力した文字列から
image.png

1文字ずつのオブジェクトをつくる!!!!('◇')ゞ
image.png
image.png

実装内容

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

public InputField inputField;
public GameObject innerBox; //文字たちを格納するための親オブジェクト(空オブジェクト)
private string speakText;

public void Generate3DText()
{
        Debug.Log("Generate3DTextStart()");

        speakText = inputField.text;

        for(int i = 1; i <= speakText.Length; i++)
        {
            Debug.Log("i = " + i + ", speakText.Length = " + speakText.Length);
            // プレハブ生成(この時点では、まだ、空のText)
            GameObject word = (GameObject)Resources.Load("Word");
            var newObj = Instantiate(word, new Vector3(0.0f, 0.0f, 0.0f), Quaternion.identity) as GameObject;
            // 生成された各オブジェクトに文字を1文字ずつ入れる
            newObj.GetComponent<TextMesh>().text = speakText.Substring(i-1,1);
            // 生成された各オブジェクトの名前を変更
            newObj.name = "word" + "(" + speakText.Substring(i-1,1) + ")";
            // 各文字の位置を調整
            newObj.transform.parent = innerBox.transform;
            newObj.transform.localPosition = new Vector3(160.0f*(i-1), -151.0f, 0.0f);
            innerBox.transform.localPosition = new Vector3(-80.0f*(i-1), 0.0f, 0.0f);
        }
}

補足

"Word"という名前のプレハブを用意してます。(Wordの中身は、ただのTextMeshでok)
3D空間に表示したかったので、TextMeshを使ってますが、Textに直しても使えます。
(speakTextという名前なのは、音声認識からとってきた文字列だったからです…('◇')ゞ(InputField用にスクリプトを変えたなごり…))

2
1
0

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
2
1