ロバメモ - 素人のUnity覚書と奮闘記

素人のUnity覚書と奮闘記

パラパラアニメーションを作る

連続画像を用いて動画を作成したい。
Flashで作成していたころによく使った手法をUnityでもやりたかったので、その方法をメモ。

unityには、アニメーションを作るツールのようなものがあるんだけど、それを使うとどうも重い。
特にiPhoneはすぐに落ちる。
どうやら、一度に容量の大きい画像を複数枚読み込むのが無理みたい。
ということは、プログラムで一枚づつ、読み込み→表示→破棄を繰り返すしかなさそう。

1. 画像をリソースに入れる

今回は、エンディングの動画を作りたいので、endingフォルダに連番の画像を入れて、それをResourceフォルダに入れる。
スプライトへのパスは、ending/endingMovie0001~18 となる。
別に0番からでもOK。
連番にしといたほうが後が楽。
f:id:nico-taniku:20170410121220p:plain

2. Imageオブジェクトを配置

キャンバスにImageを追加して、1枚目を設定しておく。
f:id:nico-taniku:20170410121252p:plain

3. プログラム

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

public class Ending : MonoBehaviour
{

    public Image image;
    int max = 18;
    int counter = 1;
    float passtime = 0.1f;
    
    // Update is called once per frame
    void Update ()
    {
        passtime -= Time.deltaTime;
        if (passtime <= 0.0) {
            passtime = 0.1f;
            counter++;
            if (counter <= max) {
                Sprite spr;
                if (counter < 10) {
                    spr = Resources.Load ("ending/endingMovie000" + counter);
                } else {
                    spr = Resources.Load ("ending/endingMovie00" + counter);
                }
                image.sprite = spr;
            } else {
                OnComplate ();
            }
        }
    }

    void OnComplate ()
    {
        GameObject.Find ("FadeOut").GetComponent ().OnStart ();
    }
}

変数について

imageは、手順2で配置したImageをインスペクターで設定しておく。
maxは、画像の総数。
counterは、最初の画像番号を設定しておく。
passtimeは、画像から次の画像までの秒数を設定。1秒/FPSで設定してあとは微調整する感じ。

スプライトの設定

if (counter < 10) {
    spr = Resources.Load ("ending/endingMovie000" + counter);
} else {
    spr = Resources.Load ("ending/endingMovie00" + counter);
}

この部分で、読み込むスプライトを指定している。
番号を0001と4桁にしてるので、ちょっと面倒になってる。

完了後の処理

OnComplete()に、完了後の処理を書く。