通过c#脚本创建unity 2d动画



我对unity非常陌生,刚刚开始我的第一个项目。我想知道是否有可能通过脚本来改变动画中使用的精灵,而不是手工操作。

伪代码 示例
Sprite[] animSr = new Sprite[2]{SpriteA, SpriteB};
int animSampleRate = 60;
int[] framesIndex = new int[2]{ 0, 60};
Animation anim = new Animation();
//pseudocode
anim.SetSampleRate(animSampleRate);
anim.UpdateFrame(Sprite = animSr[0], FrameInd = framesIndex[0]);
anim.UpdateFrame(Sprite = animSr[1], FrameInd = framesIndex[1]);

因此动画应该是这样的

我用2个脚本制作了动画。AnimationGerator.cs


using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class AnimationGenerator : MonoBehaviour
{
private static AnimationGenerator a_instance;
public static AnimationGenerator Instance
{
get
{
return a_instance;
}
}
public List<Sprite> Sprites;
private void Start()
{
a_instance = this;
}
public AnimationClip Generate()
{
AnimationClip animClip = new AnimationClip();
animClip.frameRate = 25;   // FPS
EditorCurveBinding spriteBinding = new EditorCurveBinding();
spriteBinding.type = typeof(Image);
spriteBinding.path = "";
spriteBinding.propertyName = "m_Sprite";
ObjectReferenceKeyframe[] spriteKeyFrames = new ObjectReferenceKeyframe[Sprites.Count];
for (int i = 0; i <Sprites.Count; i++)
{
spriteKeyFrames[i] = new ObjectReferenceKeyframe();
spriteKeyFrames[i].time = ((float)i / 25); 
spriteKeyFrames[i].value = Sprites[i];
}
AnimationUtility.SetObjectReferenceCurve(animClip, spriteBinding, spriteKeyFrames);
return animClip;
}
public void ClearSprites()
{
Sprites.Clear();
}
}

AnimationGeneratorEditor.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
public class AnimationGeneratorEditor : EditorWindow
{
public GameObject obj = null;
string objNames = "";
[MenuItem("Animation/AnimationGenerator")]
public static void ShowWindow()
{
EditorWindow.GetWindow(typeof(AnimationGeneratorEditor));
}
static void Initialize()
{
AnimationGeneratorEditor window = (AnimationGeneratorEditor)EditorWindow.GetWindow(
typeof(AnimationGeneratorEditor),
true,
"Animation Generating Tools"
);
window.position = new Rect(0, 0, 250, 150);
}
public void OnGUI()
{
string path = "";
objNames = EditorGUI.TextField(new Rect(10, 25, position.width - 20, 20),
path,
objNames);
if (GUI.Button(new Rect(10, 45, position.width - 20, 20), "Generate"))
{
AnimationClip animClip = FindObjectOfType<AnimationGenerator>().Generate();
AssetDatabase.CreateAsset(animClip, "assets/" + objNames + ".anim");
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
if (GUI.Button(new Rect(10, 68, position.width - 20, 20), "Clear Sprites"))
{
FindObjectOfType<AnimationGenerator>().ClearSprites();
}
}
}

相关内容

  • 没有找到相关文章

最新更新