Skip to content

Instantly share code, notes, and snippets.

@kunofellasleep
Last active June 11, 2019 08:28
Show Gist options
  • Save kunofellasleep/99481a87e8b801e14b7623c1d7128776 to your computer and use it in GitHub Desktop.
Save kunofellasleep/99481a87e8b801e14b7623c1d7128776 to your computer and use it in GitHub Desktop.
Unity連番画像再生
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 連番画像再生
/// </summary>
public class RenbanPlayer : MonoBehaviour
{
//入力画像のフレームレート
public float framerate = 30;
//Resoucesフォルダからのパス
public string resourcePath = "Textures/SynchroTitleRenban";
//ファイル名のprefix
public string prefixName = "sprite_";
//合計コマ数
public int length = 24;
//ループ再生設定
public bool isLoop = false;
private Image targetImage;
private int currentFrame;
private float frameTime;
private bool isPlaying;
/// <summary>
/// 再生
/// </summary>
public void Play()
{
isPlaying = true;
}
/// <summary>
/// 一時停止
/// </summary>
public void Pause()
{
isPlaying = false;
}
/// <summary>
/// リセット
/// </summary>
public void Reset()
{
currentFrame = 1;
frameTime = 0.0f;
}
private void Start()
{
targetImage = GetComponent<Image>();
if(!targetImage) {
Debug.LogWarning("Imageコンポーネントをゲームオブジェクトにアタッチs");
}
this.Reset();
}
private void Update()
{
if (!isPlaying) return;
// フレーム時間更新
frameTime += Time.deltaTime;
// フレームに更新がある場合
if (frameTime > 1f / framerate)
{
frameTime = 0.0f;
currentFrame++;
// ループ再生の場合は最後のコマで最初に戻る
if (currentFrame > length && isLoop) currentFrame = 1;
// ループ再生でない場合は最後のコマで再生終了
if (currentFrame >= length && !isLoop) isPlaying = false;
// 現在のフレームを取得して表示
var filename = resourcePath + "/" + prefixName + currentFrame;
Sprite sprite = Resources.Load<Sprite>(filename);
targetImage.sprite = sprite;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment