using UnityEditor;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Animation2DGenerator : MonoBehaviour {
public Texture2D texture;
public Sprite sprite;
public Animation myAnimation;
// Use this for initialization
void Start () {
int frameWidth = 255, frameHeight = 255;
string[] pngPaths = new string[] {
"Assets/Animation2DGenerator/TestData/AnimFrame1.png",
"Assets/Animation2DGenerator/TestData/AnimFrame2.png",
"Assets/Animation2DGenerator/TestData/AnimFrame3.png" };
texture = new Texture2D(frameWidth, frameHeight);
Sprite[] sprites = new Sprite[pngPaths.Length];
int[] durations = new int[pngPaths.Length];
for (int i = 0; i < pngPaths.Length;i++)
{
texture.LoadImage(System.IO.File.ReadAllBytes(pngPaths[i]));
texture.filterMode = FilterMode.Point;
sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0), 100f);
sprites[i] = sprite;
durations[i] = 30 * (i + 1);
}
// sprite のテスト。 3 が表示された。
SpriteRenderer sr = gameObject.AddComponent<SpriteRenderer>();
sr.sprite = sprite;
// animation
AnimationClip animClip = new AnimationClip();
animClip.frameRate = 12f;
animClip.wrapMode = WrapMode.Loop;
// First you need to create e Editor Curve Binding
EditorCurveBinding curveBinding = new EditorCurveBinding();
// I want to change the sprites of the sprite renderer, so I put the typeof(SpriteRenderer) as the binding type.
curveBinding.type = typeof(SpriteRenderer);
// Regular path to the gameobject that will be changed (empty string means root)
curveBinding.path = "";
// This is the property name to change the sprite of a sprite renderer
curveBinding.propertyName = "m_Sprite";
// An array to hold the object keyframes
ObjectReferenceKeyframe[] keyFrames = new ObjectReferenceKeyframe[pngPaths.Length];
for (int i = 0; i < pngPaths.Length; i++ )
{
keyFrames[i] = new ObjectReferenceKeyframe();
// set the time
keyFrames
[i
].
time = durations
[i
]; // set reference for the sprite you want
// tileid は 0 から始まるので gid にするために 1 加算する。
keyFrames[i].value = sprites[i];
}
AnimationUtility.SetAnimationType(animClip, ModelImporterAnimationType.Generic);
AnimationUtility.SetObjectReferenceCurve(animClip, curveBinding, keyFrames);
AssetDatabase.CreateAsset(animClip, "Assets/Animation2DGenerator/TestData/anim1.anim");
EditorUtility.SetDirty(animClip);
// animator コンポーネントを設定
myAnimation = gameObject.AddComponent<Animation>();
myAnimation.AddClip(animClip, "anim1");
myAnimation.Play("anim1");
myAnimation.wrapMode = WrapMode.Loop;
myAnimation.transform.position = new Vector3(-2, 0, -1);
}
// Update is called once per frame
void Update () {
}
}