0
votes

I have a simple 12-frame 2D sprite animation in Unity (2019.2.21f1), which I created by making a sprite sheet and using the Unity sprite editor to slice the sprite sheet into the animation's individual frames.

I would like to execute certain code on frames 3, 7, and 10 of the animation.

Is it possible, in code (C#), to get the frame that is currently being displayed in the animation? Or is there some other way of executing code exactly when frames 3, 7, or 10 are being displayed?

1
HI Ben Rubin, that should work thanks :) If you're willing to make this into an answer, I'll gladly accept it - it doesn't directly answer the question in the title, but it answers the question in my OP's last sentence, and gives me the functionality I wanted.ChrisC
Glad to hear it solves your problem, I'll post it as the answer.Ben Rubin

1 Answers

0
votes

You could figure out when the third frame runs purely in code, but the recommended (and far easier) way of doing this is to use Animation Events.

Here's an example of what it would look like to call some code on the third frame on an animation. I circled the button you have to click on to add an animation event. Once you add your event, drag it to the frame or time when you want it to execute (also circled). Then click on the animation event and enter the name of the function that you want to be called when the event executes. You can optionally pass a parameter to your function by entering that underneath the function name.

When the event fires, it'll look for that function on a script that's attached to the same game object. Then you can do whatever you want to inside that function. If you have a typo in one of the names or you don't have a matching function attached to your game object, you'll get an error in the Unity Editor when that event fires.

My example below will call DoSomethingOnThirdFrame when the animation reaches the third frame.

enter image description here