今回は、ファイルシステムに保存した画像を、コマ送り動画として表示させてみます。
サンプルソースは最後にあり。
連番画像を用意する
下のような感じで 00.png 〜 99.png みたいな連番画像を作成しておきます。
連番ファイルの情報を一気に取得する
System.IO.DirectoryInfo クラスを使用し、ディレクトリの中から png ファイルをごっそり取得。
ファイルからテクスチャを作成する
ファイルのバイナリを読み込んでTexture2Dオブジェクトを作成する必要があります。
これはSystem.IO.FileStreamクラスで読み込んだファイルのバイナリを、Texture2D.LoadImageメソッドに渡すことで可能。
RawImageコンポーネントに画像を表示する
ファイルから動的にテクスチャを作成するので、画像の表示にはRawImageを使用します。
Updateが呼ばれるごとに RawImage.texture プロパティを更新するだけです。(コルーチンにしたほうがいいですね)
ソース
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TextureAnim : MonoBehaviour { [SerializeField] string dirPath; // 連番画像が保存されているディレクトリ // コマ表示キュー Queue<System.IO.FileInfo> fileQueue; // 表示用テクスチャ Texture2D tex; RawImage AnimImage; void Start () { AnimImage = GetComponent<RawImage>(); // ディレクトリ内のpngファイル一覧を取得 // -> キューに入れる System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(dirPath); fileQueue = new Queue<System.IO.FileInfo>(info.GetFiles("*.png")); // テクスチャオブジェクトを作成しておく tex = new Texture2D(256, 256, TextureFormat.RGB24, false); AnimImage.texture = Texture2D.blackTexture; } void Update () { if (fileQueue.Count <= 0) { // 全部表示したので何もしない return; } // ファイルからテクスチャデータ読み込み System.IO.FileInfo targetImage = fileQueue.Dequeue(); System.IO.FileStream stream = targetImage.OpenRead(); var data = new byte[stream.Length]; stream.Read(data, 0, (int)stream.Length); tex.LoadImage(data); // RawImageにテクスチャとして設定 AnimImage.texture = tex; } }