元 Flash エンジニアから見る Unity の Timeline ~ラベル編~

前置き・ Flash のタイムライン

Flash (現 Animate) のタイムラインは、任意のフレームにラベルを設定しておき、

this.gotoAndPlay("ラベル名");

とか書いてやれば、どこからでもそのラベルにジャンプできるという、大変便利な機能がありました。

この記事では、 Unity の Timeline でも Flash のラベルみたいなことを実現するための手法を紹介します。

Control Clip を Label 代わりにする

まず、 Timeline に Control Track を追加します。

そして、 Track を右クリックし、「Add Control Playable Asset Clip」を選択して、 Control Clip を作成します。

f:id:Gigacee:20180709194523p:plain

この Control Clip ですが、図のように Inspector から好きな名前を付けることができます。

これを利用して、ラベルのようなものを作ろうというわけです。

そうして出来上がったのがコチラ。ついでに Track 名も "Label" にしています。

f:id:Gigacee:20180709201442g:plain
判りやすいように、 cube をアニメーションさせています。

スクリプトから Timeline を制御

次に、設定した各ラベルにジャンプしたりするためのスクリプトを書きます。

考え方としては単純で、 GetClips() で Label トラックの全クリップ(scene1 とか)を取得して、それぞれのクリップ名をキー、クリップの開始位置を値とした連想配列を作り、ラベル情報として取っておくだけです。

using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;

public class TimelineController : MonoBehaviour
{
    PlayableDirector timeline;
    Dictionary<string, double> labels;

    void Start()
    {
        timeline = GetComponent<PlayableDirector>();

        labels = ((TimelineAsset)timeline.playableAsset)
            .GetOutputTracks()
            .Single(x => x.name == "Label")
            .GetClips()
            .ToDictionary(
                clip => clip.displayName,
                clip => clip.start);
    }

    public void GotoAndPlay(string label)
    {
        timeline.time = labels[label];
        timeline.Evaluate();
        timeline.Play();
    }

    public void GotoAndStop(string label)
    {
        timeline.time = labels[label];
        timeline.Evaluate();
        timeline.Pause();
    }

    public void Play()
    {
        timeline.Play();
    }

    public void Stop()
    {
        timeline.Pause();
    }
}

このスクリプトを、 Timeline がアタッチされているのと同じ GameObject にアタッチすれば OK 。

あとは、適当な UI で関数を呼び出してあげれば……。

f:id:Gigacee:20180709205814g:plain

この通り! Flash の gotoAndPlay("ラベル名")gotoAndStop("ラベル名") のように、任意のラベルにジャンプできるようになりました!

The coloring of this site is Dracula PRO🧛🏻‍♂️
This website uses the FontAwesome icons licensed under CC BY 4.0.

2020 GIGA CREATION