Accurate playback duration of any animation clip in Unity3D by using Animator animation state machine

Keywords: C# Unity

Unity3d 4 and previous versions of animation for animation play, can directly obtain its play duration. But animator is used to play animation in 5.x and later versions.

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

Many people use GetCurrent Animator StateInfo and GetNext Animator StateInfo to get how long they play under animator, but this is not the final verification solution.

The following is the correct and accurate posture for any animation clip to be played accurately for a long time through the Animator animation state machine:

/// Get the duration of animation clip playing of animator
///@ MarsZ December 19, 2017 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 (original origin address, reprinted please retain)

Posted by Headache on Fri, 08 Feb 2019 10:15:18 -0800