はじめに
こんにちは、のんびりエンジニアのたっつーです。
ブログを運営しているのでよろしければ見てください。
文字をタイピング風にアニメーションさせれると嬉しいよねって事で、以下のTwitterの後半にできる「RIKAI !!」をアニメーションで表示するスクリプトを作った。
Unity の Timeline にテキストを逐次で出すスクリプトを書いてみた。日本語は使い方忘れたので明日やる!あと色々派手にする予定。 pic.twitter.com/98NR3XMf4k
— たっつー(ささきたかし) (@kingyo222) 2018年9月6日
実装
TextMeshPro で文字を追加
Unityの最新版では「TextMeshPro」が標準で使えるようになっているのでこれを利用します、なお標準ではフォントがアルファベットしか使えないので日本語(ひならが、カタカナ、漢字)を使う場合は、フォントデータをダウンロードして使う必要があります。
タイピング風のアニメーションスクリプトを追加
- 以下の2つのスクリプトをAssetsフォルダに追加します。
TextPlayableAsset.cs
using UnityEngine;
using UnityEngine.Playables;
[System.Serializable]
public class TextPlayableAsset : PlayableAsset
{
public ExposedReference<GameObject> charaObj;
// public string text;
// Factory method that generates a playable based on this asset
public override Playable CreatePlayable(PlayableGraph graph, GameObject go)
{
var behaviour = new TextPlayableBehaviour();
behaviour.charaObject = charaObj.Resolve(graph.GetResolver());
// behaviour.text = text;
return ScriptPlayable<TextPlayableBehaviour>.Create(graph, behaviour);
}
}
using TMPro;
using UnityEngine;
using UnityEngine.Playables;
// A behaviour that is attached to a playable
public class TextPlayableBehaviour : PlayableBehaviour
{
public GameObject charaObject;
private string text;
// Called when the owning graph starts playing
public override void OnGraphStart(Playable playable) {
this.text = this.charaObject.GetComponent<TextMeshPro>().text;
this.charaObject.GetComponent<TextMeshPro>().text = "";
}
// Called when the owning graph stops playing
public override void OnGraphStop(Playable playable) {
this.charaObject.GetComponent<TextMeshPro>().text = this.text;
}
// Called when the state of the playable is set to Play
public override void OnBehaviourPlay(Playable playable, FrameData info) {
}
// Called when the state of the playable is set to Paused
public override void OnBehaviourPause(Playable playable, FrameData info) {
}
// Called each frame while the state is set to Play
public override void ProcessFrame(Playable playable, FrameData info, object playerData)
{
// PlayableTrackのClip上でシークバーが移動するたびに呼ばれ続ける(PrepareFrameの後)
if (charaObject == null) { return; }
var percent = (float)playable.GetTime() / (float)playable.GetDuration();
this.charaObject.GetComponent<TextMeshPro>().text =
this.text.Substring(0, (int)Mathf.Round(this.text.Length * percent));
}
}
Timeline を追加
ソースコード
遅くなりましたがソースコード公開します(2018/09/24)
https://github.com/fastsystem/unity-text-typing-animation
まとめ
Timeline のスクリプトは意外と簡単で、進捗(0%~100%)で何かさせたいような作業を自分が考えたスクリプトに簡単に置き換え可能になります、そこで今回のような物を作成してみました。
ぜひみなさんも使ってみていただければと思います。
よければ ブログ「初心者向けUnity情報サイト」の方にも色々記載しているのでぜひご参照いただければと思います。