• Unity
  • Set looping animation in update without restarting it.

What's the best way to set a looping animation inside an update method without restarting the animation?
I have the following code but I'm afraid it might be inefficient.

void Update()
{
   if (IsPlaying(0, animation)) return;
   skeletonAnimation.AnimationState.SetAnimation(0, animation, true);
}

public bool IsPlaying(int trackIndex, string animationName)
{
   var animation = skeletonAnimation.AnimationState.Data.SkeletonData.FindAnimation(animationName);
   var trackEntry = skeletonAnimation.AnimationState.GetCurrent(trackIndex);
   if (trackEntry == null) return false;
   return trackEntry.Animation == animation;
}
Related Discussions
...

You can change TrackEntry loop instead of starting the animation again.

Aside from that, it would be better to store the Animation for the string animation, unless this variable changes and cannot be cached in advance in Start().

Thanks for the reply.

It seems setting TrackEntry to loop does not help as the original animation is already set to loop.
To clarify when you use SetAnimation on every frame, you'll only see the first frame of the animation.

I guess I could use a cached reference to the animation, it would look like the following code example.

The question I have now – is there a way to avoid having two variables for one animation? Like I'd love to serialize Spine.Animation straight away.

public class AnimationLoopTest : MonoBehaviour
{
   [SerializeField] SkeletonAnimation skeletonAnimation;

   [SerializeField]
   [SpineAnimation(dataField: "skeletonAnimation", fallbackToTextField: true)]
   string animationName;

   Spine.Animation spineAnimation;

   void Start()
   {
      spineAnimation = skeletonAnimation.skeleton.Data.FindAnimation(animationName);
   }

   void Update()
   {
      if (skeletonAnimation.AnimationState.GetCurrent(0).Animation != spineAnimation)
      {
         skeletonAnimation.AnimationState.SetAnimation(0, spineAnimation, true);
      }
   }
}
IggyZuk a écrit

The question I have now – is there a way to avoid having two variables for one animation? Like I'd love to serialize Spine.Animation straight away.

AnimationReferenceAsset serves this purpose. The example scene Spine Examples/Getting Started/3 Controlling Animation Continued shows how to use them.

IggyZuk a écrit

It seems setting TrackEntry to loop does not help as the original animation is already set to loop.
To clarify when you use SetAnimation on every frame, you'll only see the first frame of the animation.

Then I misunderstood your question. I thought you wanted to change a non-looping animation to looping afterwards.

That's perfect thank you for the help! 🙂

Glad it helped, thanks for letting us know!