# How to Fetch a Frame Number from Animation Clip

I'm trying to find out how to fetch the frame number from an animation clip accurately. I don't want to get a value between 0 and 1 that shows as a percentage-as-a-decimal how much of the animation has played (example: 0.5 = the 5th frame of 10 frames) because it doesn't seem to be accurate. This also seems impractical, so is there a way to accurately fetch a frame number from an animation clip?

Thanks.

• Converting AnimationState.time to a frame number would just involve multiplying it by your designated frame rate and flooring the result, would it not? Is this not giving the values you want? – DMGregory Nov 12 '18 at 21:53
• I haven't tried that out. Can you elaborate on that? – BobDev Nov 12 '18 at 22:01
• Just want to point out that animation in unity doesn't have discrete integer frames. Instead the actual "frame" number could be any floating point, so anything like 1.0, 2.72, 3.5, 20.212 etc. are all possible. – ZombieTfk Nov 12 '18 at 22:38

Assuming you're only using a single layer in your Animator, where MyAnimator is a Animator component.

MyAnimator.GetCurrentAnimatorClipInfo(0)[0].clip.length * (MyAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1) * MyAnimator.GetCurrentAnimatorClipInfo(0)[0].clip.frameRate;


Will return the current "frame", which you can then round appropriately to get an integer value, if that's what you would like.

We mod the current animation state info's normalizedTime by 1, because looping animations will go above 1.

... And if you have multiple animations playing at once on a single layer (such as when transitioning from one animation state to another), you may need to check the weight(s) of each animation, but you'll probably be able to get away with the above.

To be honest, relying on this value may or may not be the best route, depending on what you want to accomplish. For any frame/time dependent behavior you want to tie into unity's animation system I'd recommend looking at animation events.

• I'm trying to trigger another animation clip when a combination of 2 buttons are pressed to switch to the corresponding frame. Example: when the 2nd frame of the first animation is played and when the combination of two buttons are pressed, the animation clip will switch to the 2nd frame of the other animation clip. – BobDev Nov 12 '18 at 23:41
• Ah, in that case, you may want to take a look at this method, you can pass in the name of the animation state you wish to play, and the current normalizedTime property i referenced in the above snippet to play your animation from a given point. – ZombieTfk Nov 12 '18 at 23:51