public void Create(AnimationClip sourceClip,string targetPath = "Assets/targetClip.anim")
{
//源clip
if (sourceClip == null) return;
//载入目标clip
var targetClip = AssetDatabase.LoadAssetAtPath<AnimationClip>(path);
if (targetClip == null)
{
targetClip = new AnimationClip();
AssetDatabase.CreateAsset(targetClip, path);
}
//复制源clip设置
var setting = AnimationUtility.GetAnimationClipSettings(targetClip);
setting.loopTime = sourceClip.isLooping;
targetClip.frameRate = sourceClip.frameRate;
AnimationUtility.SetAnimationClipSettings(targetClip, setting);
targetClip.ClearCurves();
//设置路径为空 (timeline用)
var relativePath = "";
//获得曲线集合
var curves = AnimationUtility.GetCurveBindings(sourceClip);
foreach (var binding in curves)
{
if (binding.propertyName.Contains("m_LocalScale")) continue;
var curve = AnimationUtility.GetEditorCurve(sourceClip, binding);
//Debug.Log(binding.path + " " + binding.propertyName + " " + binding.type + " Keys: " + curve.keys.Length);
var lastT = curve[curve.length - 1].time;
var lastV = (float)System.Math.Round((double)curve[curve.length - 1].value, 2);
//压缩帧数
var length = curve.length / 2;
var keys = new Keyframe[length];
var last = false;
for (int i = 0; i < length; i++)
{
var _key = curve[i * 2];
if (_key.time == lastT)
{
keys[i].time = _key.time;
last = true;
}
else
{
//压缩精度(小数点两位)
keys[i].time = (float)System.Math.Round((double)_key.time, 2);
}
keys[i].value = (float)System.Math.Round((double)_key.value, 2);
}
//还原最后一帧数据,保持clip时长。
if (last == false)
{
System.Array.Resize(ref keys, keys.Length + 1);
keys[keys.Length - 1] = new Keyframe(lastT, lastV);
}
var newcurve = new AnimationCurve(keys);
targetClip.SetCurve(relativePath, binding.type, binding.propertyName, newcurve);
}
// 保存
AssetDatabase.SaveAssets();
}
网友评论