用于从 Unity 组件读取和写入值的动画实用程序函数。
using System.Collections.Generic; using UnityEngine; using UnityEngine.Animations; using UnityEditor; using Unity.Collections; using System.Linq;
public class AnimationClipPlayer : MonoBehaviour { public AnimationClip animationClip; public float time;
List<AnimationCurve> curves;
NativeArray<BoundProperty> floatProperties; NativeArray<BoundProperty> intProperties; NativeArray<float> floatValues; NativeArray<int> intValues;
void Start() { var editorCurveBindings = AnimationUtility.GetCurveBindings(animationClip); editorCurveBindings = editorCurveBindings.Where(editorCurveBinding => editorCurveBinding.type != typeof(Transform) && !editorCurveBinding.isPPtrCurve && !editorCurveBinding.isDiscreteCurve ).ToArray();
curves = new List<AnimationCurve>(editorCurveBindings.Length); for (var i = 0; i < editorCurveBindings.Length; i++) { curves.Add(AnimationUtility.GetEditorCurve(animationClip, editorCurveBindings[i])); }
var genericBindings = new NativeArray<GenericBinding>(AnimationUtility.EditorCurveBindingsToGenericBindings(editorCurveBindings), Allocator.Temp); GenericBindingUtility.BindProperties(gameObject, genericBindings, out floatProperties, out intProperties, Allocator.Persistent);
floatValues = new NativeArray<float>(floatProperties.Length, Allocator.Persistent); intValues = new NativeArray<int>(intProperties.Length, Allocator.Persistent); }
private void OnDestroy() { floatProperties.Dispose(); floatValues.Dispose(); intProperties.Dispose(); intValues.Dispose(); }
// Update is called once per frame void Update() { for (int i = 0; i < curves.Count; i++) { floatValues[i] = curves[i].Evaluate(time); }
GenericBindingUtility.SetValues(floatProperties, floatValues); } }
BindProperties | 检索由 GenericBinding 列表定义的 BoundProperty 列表。 |
CreateGenericBinding | 检索表示与 GameObject 或其组件关联的特定属性的 GenericBinding。 |
GetAnimatableBindings | 检索特定 GameObject 的可动画绑定。 |
GetCurveBindings | 从动画剪辑中检索曲线绑定。 |
GetValues | 检索每个 [[BoundProperty]] 的浮点或整数值。 |
SetValues | 设置每个 [[BoundProperty]] 的浮点或整数值。 |
UnbindProperties | 取消绑定并释放 BoundProperty 列表使用的所有资源。 |