Aditya Nambidi
Aditya Nambidi

Reputation: 111

Unity - How to find which frame my animation is on?

So I am using Unity and C# for my game. I want something to happen when the animation is on a particular frame. how do I detect what frame the animation is on?

Upvotes: 1

Views: 9186

Answers (4)

toonsend
toonsend

Reputation: 1342

You can work from SpriteRenderer, which will tell you the name of the sprite that the animator is currently displaying.

GetComponent<SpriteRenderer>().sprite.name;

Upvotes: 0

Tommy
Tommy

Reputation: 359

You can achieve that by using Animation Events.

Fist, create a function in your script to receive the event. Let's say your function is called "OnAnimationHalfWay".

Then, go to your animation and add an animation event by selecting your desired frame and clicking the "add event" button.

After that, click on the little event flag thing you just created.

Lastly, go to your inspector and in the "function" property, choose whatever the name of your function is, in my case, it's "OnAnimationHalfWay".

Hope this helped you!

Upvotes: 2

If you want something to happen in a particular frame you should use events on animations.

Here is the oficial documentation to achieve it:

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

In your animation, select the frame and click the event button: enter image description here

(Image from https://docs.unity3d.com/)

Then you must set the function to be called. And everytime the animation goes through this frame, the function will be called.

Upvotes: 0

Christopher
Christopher

Reputation: 61

AnimationState.normalizedTime will give you the progress of the animation in a value between 0 and 1, you can extrapolate on this by converting it to your frame rate.

if (myAnim.GetCurrentAnimatorStateInfo(0).normalizedTime == .5f) {// the animation is halfway}

Upvotes: 2

Related Questions