以下是直接获取动画控制器中的某个动画状态的长度.
使用代码:
AnimatorExt.GetClipLength(m_Animator, "Run")
public static class AnimatorExt
{///获取动画状态机animator的动画clip的播放持续时长public static float GetClipLength(Animator animator, string clipName){if (null == animator ||string.IsNullOrEmpty(clipName) ||null == animator.runtimeAnimatorController)return 0;// 获取所有的clips RuntimeAnimatorController ac = animator.runtimeAnimatorController;var clips = ac.animationClips;if (null == clips || clips.Length <= 0) return 0;AnimationClip clip;for (int i = 0, len = clips.Length; i < len; ++i){clip = ac.animationClips[i];if (null != clip && clip.name == clipName)return clip.length;}return 0f;}
}
利用动画状态的哈希值播放动画
private int idel_Hash;private Animator m_Animator;private void Start(){m_Animator = GetComponent<Animator>();idel_Hash = Animator.StringToHash("Idel");//这里用的是静态方法m_Animator.Play(idel_Hash);}
playable动画相关
第一种办法,直接播放对应动画片段(不需要创建相应的动画控制器,但是需要一个组件)
public AnimationClip clip1;public AnimationClip clip2;PlayableGraph playableGraph;void Update()
{if (Input.GetKeyDown(KeyCode.V)){AnimationPlayableUtilities.PlayClip(GetComponent<Animator>(), clip1, out playableGraph);}if (Input.GetKeyDown(KeyCode.C)){AnimationPlayableUtilities.PlayClip(GetComponent<Animator>(), clip2, out playableGraph);}
}
第二种,创建相应的playableGraph
private void Start(){playableGraph = PlayableGraph.Create("TestPlayableGraph");var animationOutputPlayable = AnimationPlayableOutput.Create(playableGraph, "AnimationOutput", GetComponent<Animator>());var jumpAnimationClipPlayable = AnimationClipPlayable.Create(playableGraph, clip1);//AnimationPlayableOutput只有一个输入口,所以port为0animationOutputPlayable.SetSourcePlayable(jumpAnimationClipPlayable, 0);playableGraph.Play();}
playable没找到相关的速度控制办法,还是乖乖的研究老的动画系统。
不得不说Unity的动画系统,真是坑太多了。一个简单的2D游戏动画控制这么难搞