• RuntimesUnity
  • How to get the current animation frame in code?

Here is a test example of my code.

private void FixedUpdate() {

  if (idle == true) SetAnimation(IdleAnimation, true, 1 f);
  if (run == true) SetAnimation(RunAnimation, true, 1 f);
}

private string currentAnimation;
private TrackEntry currentTrackEntry;

public void SetAnimation(AnimationReferenceAsset animation, bool loop, float timeScale) {
  if (animation.name.Equals(currentAnimation)) return;

  currentTrackEntry = skeletonAnimation.state.SetAnimation(0, animation, loop);
  currentTrackEntry.TimeScale = timeScale;
  currentAnimation = animation.name;
}

This code sets the animation.

The fixed update method checks the player's state every frame and if the player is waiting, sets the waiting animation.
And if the player is running - a running animation.

As you can see from the code, if in the current frame the name of the previous animation matches the one being set, we do not restart the animation, which is obvious.

Is it possible to somehow get the number of the current animation frame?
I need exactly the frame number, as in the editor.

Related Discussions
...

To get the current animation frame number in code, you can use the AnimationTime property of the TrackEntry class, which gives you the current time in seconds of the animation. Since Spine animations are typically authored at 30 frames per second (fps), you can convert this time to frame numbers by multiplying the time by the fps. Here's how you could modify your code to get the current frame number:

FixedUpdate()
{
    if (idle==true) SetAnimation(IdleAnimation, true, 1f);
    if (run==true) SetAnimation(RunAnimation, true, 1f);

    // Assuming your animations are authored at 30 fps.
    float currentFrame = currentTrackEntry.AnimationTime * 30;
    int currentFrameNumber = Mathf.FloorToInt(currentFrame);
    Debug.Log("Current Frame: " + currentFrameNumber);
}

private string currentAnimation;
private TrackEntry currentTrackEntry;

public void SetAnimation(AnimationReferenceAsset animation, bool loop, float timeScale)
{
    if (animation.name.Equals(currentAnimation)) return;

    currentTrackEntry = skeletonAnimation.state.SetAnimation(0, animation, loop);
    currentTrackEntry.TimeScale = timeScale;
    currentAnimation = animation.name;
}

This approach calculates the frame number based on the animation's playback time and assumes a default frame rate of 30 fps. If your animations use a different frame rate, adjust the multiplication factor accordingly.