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


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

https://docs.unity3d.com/Manual/AnimationOverview.html 

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;
	}
}

Ref:
1、https://docs.unity3d.com/ScriptReference/Animator.html
2、https://docs.unity3d.com/ScriptReference/RuntimeAnimatorController.html
3、http://www.u3dnotes.com/archives/1131 (原創首發地址,轉載請保留)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM