using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using MotionFramework.Experimental.Animation; [RequireComponent(typeof(Animator))] public class AnimBehaviour : MonoBehaviour { [Serializable] public class AnimationWrapper { public int Layer; public WrapMode Mode; public AnimationClip Clip; } private AnimPlayable _animPlayable; private Animator _animator; [SerializeField] protected AnimationWrapper[] _animations; [SerializeField] protected bool _playAutomatically = true; [SerializeField] protected bool _animatePhysics = false; /// /// 自动播放动画 /// public bool PlayAutomatically { get { return _playAutomatically; } set { _playAutomatically = value; } } /// /// 物理更新模式 /// public bool AnimatePhysics { get { return _animatePhysics; } set { _animatePhysics = value; _animator.updateMode = _animatePhysics ? AnimatorUpdateMode.AnimatePhysics : AnimatorUpdateMode.Normal; } } public void Awake() { _animator = GetComponent(); _animator.updateMode = _animatePhysics ? AnimatorUpdateMode.AnimatePhysics : AnimatorUpdateMode.Normal; _animPlayable = new AnimPlayable(); _animPlayable.Create(_animator); // 添加列表动作 for (int i = 0; i < _animations.Length; i++) { var wrapper = _animations[i]; if (wrapper == null || wrapper.Clip == null) continue; wrapper.Clip.wrapMode = wrapper.Mode; _animPlayable.AddAnimation(wrapper.Clip.name, wrapper.Clip, wrapper.Layer); } } public void OnEnable() { _animPlayable.PlayGraph(); if (PlayAutomatically) { var wrapper = GetDefaultWrapper(); if (wrapper != null) { Play(wrapper.Clip.name, 0f); } } _animPlayable.Update(float.MaxValue); } public void OnDisable() { _animPlayable.StopGraph(); } public void OnDestroy() { _animPlayable.Destroy(); } public void Update() { _animPlayable.Update(Time.deltaTime); } /// /// 获取动画状态 /// public AnimState GetState(string name) { return _animPlayable.GetAnimState(name); } /// /// 动画是否在播放中 /// public bool IsPlaying(string name) { return _animPlayable.IsPlaying(name); } /// /// 是否包含动画片段 /// public bool IsContains(string name) { return _animPlayable.IsContains(name); } /// /// 播放动画 /// public void Play(string name, float fadeLength = 0.25f) { _animPlayable.Play(name, fadeLength); } /// /// 停止动画 /// public void Stop(string name) { _animPlayable.Stop(name); } private AnimationWrapper GetDefaultWrapper() { for (int i = 0; i < _animations.Length; i++) { var wrapper = _animations[i]; if (wrapper == null || wrapper.Clip == null) continue; return wrapper; } return null; } }