Unity Animation文件优化

    [MenuItem("优化动画")]
    [MenuItem("Assets/优化动画", false, 10)]
    public static void optmizeAnimation()
    {
        UnityEngine.Object[] SelectionAsset = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Unfiltered);

        for (int i = 0; i < SelectionAsset.Length; i++)
        {
            string path = AssetDatabase.GetAssetPath(SelectionAsset[i]);
            
            EditorUtility.DisplayProgressBar("优化动画", path, i * 1f / SelectionAsset.Length);

            AnimationClip clip = AssetDatabase.LoadAssetAtPath(path);

            optmizeAnimationScaleCurve(clip);
            optmizeAnimationFloat(clip);

            Resources.UnloadUnusedAssets();
            AssetDatabase.SaveAssets();

        }


        EditorUtility.ClearProgressBar();

        AssetDatabase.Refresh();
    }


    /// 
    /// 优化浮点数精度
    /// 
    static AnimationClip optmizeAnimationFloat(AnimationClip clip)
    {
        //浮点数精度压缩到f3
        AnimationClipCurveData[] curves = null;
        curves = AnimationUtility.GetAllCurves(clip);
        Keyframe key;
        Keyframe[] keyFrames;
        for (int ii = 0; ii < curves.Length; ++ii)
        {
            AnimationClipCurveData curveDate = curves[ii];
            if (curveDate.curve == null || curveDate.curve.keys == null)
            {
                //Debug.LogWarning(string.Format("AnimationClipCurveData {0} don't have curve; Animation name {1} ", curveDate, animationPath));
                continue;
            }
            keyFrames = curveDate.curve.keys;
            for (int i = 0; i < keyFrames.Length; i++)
            {
                key = keyFrames[i];
                key.value = float.Parse(key.value.ToString("f3"));
                key.inTangent = float.Parse(key.inTangent.ToString("f3"));
                key.outTangent = float.Parse(key.outTangent.ToString("f3"));
                keyFrames[i] = key;
            }
            curveDate.curve.keys = keyFrames;
            clip.SetCurve(curveDate.path, curveDate.type, curveDate.propertyName, curveDate.curve);
        }

        return clip;
    }

    /// 
    /// 优化scale曲线
    /// 
    static AnimationClip optmizeAnimationScaleCurve(AnimationClip clip)
    {
        //去除scale曲线
        foreach (EditorCurveBinding theCurveBinding in AnimationUtility.GetCurveBindings(clip))
        {
            string name = theCurveBinding.propertyName.ToLower();
            if (name.Contains("scale"))
            {
                AnimationUtility.SetEditorCurve(clip, theCurveBinding, null);
            }
        }

        return clip;
    }


参考

https://blog.uwa4d.com/archives/Optimization_Animation.html

https://answer.uwa4d.com/question/593955b6c42dc04f4d8f7341/

https://blog.uwa4d.com/archives/Loading_AnimationClip.html

https://answer.uwa4d.com/question/597b3afd58c8409c0dc7e2ca



你可能感兴趣的:(unity)