通过SerializedObject优化动画数据精度:
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
class MyUtility
{
[MenuItem("Assets/Optimize Anim")]
static public void OptimizePrecision()
{
AnimationClip clip = Selection.activeObject as AnimationClip;
string path = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);
if (clip != null)
{
// 优化anim数据精度
SerializedObject serializedObject = new SerializedObject(clip);
SerializedProperty curvesProperty = serializedObject.FindProperty("m_FloatCurves");
OptCurves(curvesProperty);
SerializedProperty rotationProperty = serializedObject.FindProperty("m_RotationCurves");
OptCurves(rotationProperty);
SerializedProperty positionProperty = serializedObject.FindProperty("m_PositionCurves");
OptCurves(positionProperty);
SerializedProperty scaleProperty = serializedObject.FindProperty("m_ScaleCurves");
OptCurves(scaleProperty);
serializedObject.ApplyModifiedProperties();
AssetDatabase.SaveAssets();
}
}
private static void OptCurves(SerializedProperty property)
{
if (property != null && property.isArray)
{
for (int i = 0; i < property.arraySize; ++i)
{
SerializedProperty curveProperty = property.GetArrayElementAtIndex(i).FindPropertyRelative("curve");
SerializedProperty keyframeProperty = curveProperty.FindPropertyRelative("m_Curve");
if (keyframeProperty != null && keyframeProperty.isArray)
{
for (int j = 0; j < keyframeProperty.arraySize; ++j)
{
SerializedProperty kf = keyframeProperty.GetArrayElementAtIndex(j);
SerializedProperty time = kf.FindPropertyRelative("time");
OptValue(time);
SerializedProperty value = kf.FindPropertyRelative("value");
OptValue(value);
SerializedProperty inSlope = kf.FindPropertyRelative("inSlope");
OptValue(inSlope);
SerializedProperty outSlope = kf.FindPropertyRelative("outSlope");
OptValue(outSlope);
}
}
}
}
}
private static void OptValue(SerializedProperty target)
{
if (target.type == "float")
target.floatValue = OptFloat(target.floatValue);
else if (target.type == "Vector3")
target.vector3Value = OptVector3(target.vector3Value);
else if (target.type == "Vector4")
target.vector4Value = OptVector4(target.vector4Value);
else if (target.type == "Quaternion")
target.quaternionValue = OptQuaternion(target.quaternionValue);
}
private static float OptFloat(float src)
{
return Mathf.Floor(src * 1000 + 0.5f) / 1000;
}
private static Quaternion OptQuaternion(Quaternion src)
{
return new Quaternion(OptFloat(src.x), OptFloat(src.y), OptFloat(src.z), OptFloat(src.w));
}
private static Vector4 OptVector4(Vector4 src)
{
return new Vector4(OptFloat(src.x), OptFloat(src.y), OptFloat(src.z), OptFloat(src.w));
}
private static Vector3 OptVector3(Vector3 src)
{
return new Vector3(OptFloat(src.x), OptFloat(src.y), OptFloat(src.z));
}
}