1. 程式人生 > >Unity3D中通過Animator動畫狀態機獲取任意animation clip的準確播放持續時長

Unity3D中通過Animator動畫狀態機獲取任意animation clip的準確播放持續時長

Unity3d 4及之前的版本中動畫的播放用的animation,可直接獲取其播放持續長度。但5.x及以後的版本中都是用animator來播放動畫了。

While Mecanim is recommended for use in most situations, Unity has retained its legacy animation system which existed before Unity 4. You may need to use when working with older content created before Unity 4. For information on the Legacy animation system, see this section

關於在animator下如何獲取其播放持續時長,很多人用的 GetCurrentAnimatorStateInfo 及 GetNextAnimatorStateInfo 等,但這個都不是最終核實的解決方案。

如下才是通過Animator動畫狀態機獲取任意animation clip的準確播放持續時長的正確的、準確的姿勢:

///獲取動畫狀態機animator的動畫clip的播放持續時長
///@MarsZ 2017年12月19日20:46:20
///site:www.u3dnotes.com
public static class AnimatorExt 
{
	public static float GetClipLength(this Animator animator,string clip) 
	{
		if(null== animator || string.IsNullOrEmpty(clip) || null== animator.runtimeAnimatorController)
		          return 0;
		RuntimeAnimatorController ac = animator.runtimeAnimatorController;
		AnimationClip[] tAnimationClips =  ac.animationClips;
		if( null == tAnimationClips || tAnimationClips.Length <= 0) return 0;
		AnimationClip  tAnimationClip ;
		for (int tCounter = 0 ,tLen = tAnimationClips.Length; tCounter < tLen ; tCounter ++) 
		{
			tAnimationClip = ac.animationClips[i];
			if(null != tAnimationClip && tAnimationClip.name == clip)
			              return tAnimationClip.Length;
		}
		return 0F;
	}
}