Maybe I misunderstand how AddAnimation works then, because I thought that would not play it instantly? Say for example the character is currently in a long animation or a looping animation, if I call AddAnimation then the new animation won't play until the end of that original one they were already playing will it?
If anyone else is interested, I've turned my code into an extension method now, like so:
public static class ExtensionMethods
{
/// <summary>
/// Plays a new animation instantly, then reverts back to any previously playing animation once the new animation has completed
/// </summary>
/// <param name="trackIndex">The animation track that will be affected</param>
/// <param name="animationName">The name of the new animation to be inserted</param>
/// <param name="loopingOnly">Only re queue previous animation if it was looping</param>
public static void InsertAnimation(this Spine.AnimationState spineAnimator, int trackIndex, string animationName,bool loopingOnly)
{
bool previousAnimationLoops = false;
Spine.Animation previousAnimation = null;
//Get the currently playing animation data
Spine.TrackEntry animationTrack = spineAnimator.GetCurrent(trackIndex);
//Only restore previous animations if they were either looping, or were not looping but had not yet completed
if (animationTrack != null && (animationTrack.Loop || (!loopingOnly && !animationTrack.Loop && !animationTrack.IsComplete)))
{
previousAnimation = animationTrack.Animation;
previousAnimationLoops = animationTrack.Loop;
}
//Play our new animation instantly
spineAnimator.SetAnimation(trackIndex, animationName, false);
if ((previousAnimation == null))
{
//If there was no previous animation playing on this track then queue up
//an empty animation to clear the track (so last frame of new animation does not get stuck on)
spineAnimator.AddEmptyAnimation(trackIndex, 0.1f, 0f);
}
else //If there was an animation previously playing
{
//Queue up the old animation to play when our new one finishes
spineAnimator.AddAnimation(trackIndex, previousAnimation, previousAnimationLoops, 0f);
}
}
}
So now whenever I want to use this functionality, I can just do this:
Spine.AnimationState spineAnimator;
...
spineAnimator.InsertAnimation(0, launchAnimationName,true);
Its obviously still running the same code as before, but it feels nicer being able to just call that on any AnimationState instance I want now 🙂 Hooray for extension methods. If anyone else wants the same functionality they can just copy and paste that class into their project and it will work straight away.