SpriteAnimation
Unityの機能を利用してきれいに作れるみたいです。
参考リンク:Unity でスプライトアニメーションを作る
しかし、ここまでガッツリと2Dのアニメーションを作りたいわけではありません。
何より、Animatorの設定を毎回やるのはタフなので
パラパラ漫画のような簡易スプライトアニメーションを作れないかと思いやってみました。
指定した秒数間隔で画像を切り替える
処理の内容としては
ImageコンポーネントのSource Image
を指定秒数後に別のTexture
に入れ替えるだけです。
以下コードです。
using System.Collections;
using UnityEngine.UI;
using UnityEngine;
# if UNITY_EDITOR
using UnityEditor;
using UnityEditorInternal;
# endif
public class SpriteAnimation : MonoBehaviour
{
[SerializeField]
Image spriteImage;
[SerializeField,HideInInspector]
Sprite[] spriteTextures;
[SerializeField]
float animationFrameSeconds;
[SerializeField]
bool debug;
public bool loop;
Coroutine runCoroutine;
void Update()
{
//デバッグキー
if (Input.GetKeyDown(KeyCode.T) && debug)
{
SpriteAnimeStart();
}
}
public void SpriteAnimeStart()
{
if (runCoroutine == null)
{
runCoroutine = StartCoroutine(SpriteAnimeCoroutine());
}
}
IEnumerator SpriteAnimeCoroutine()
{
if(loop)
{
while(loop)
{
for (int i = 0; i < spriteTextures.Length; i++)
{
spriteImage.sprite = spriteTextures[i];
yield return new WaitForSeconds(animationFrameSeconds);
}
}
runCoroutine = null;
yield break;
}
else
{
for (int i = 0; i < spriteTextures.Length; i++)
{
spriteImage.sprite= spriteTextures[i];
yield return new WaitForSeconds(animationFrameSeconds);
}
runCoroutine = null;
}
}
# if UNITY_EDITOR
[CustomEditor(typeof(SpriteAnimation))]
public class SpriteAnimationEditor : Editor
{
ReorderableList reorderableList;
void OnEnable()
{
SerializedProperty prop = serializedObject.FindProperty("spriteTextures");
reorderableList = new ReorderableList(serializedObject, prop);
reorderableList.drawHeaderCallback = (rect) => EditorGUI.LabelField(rect, "アニメーションに使用する画像");
reorderableList.drawElementCallback = (rect, index, isActive, isFocused) =>
{
SerializedProperty element = prop.GetArrayElementAtIndex(index);
rect.height -= 4;
rect.y += 2;
EditorGUI.PropertyField(rect, element, new GUIContent("フレーム" + index));
};
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
serializedObject.Update();
reorderableList.DoLayoutList();
serializedObject.ApplyModifiedProperties();
}
}
# endif
}
Inspectorはこんな感じです。
Loopのチェックをオフにすると単発再生ができて、途中でオフにすると止まります。
ReorderableListを使っているのでなかなかの使い心地です。