• Unity
  • AddAnimaiton does not respect passed delay

Related Discussions
...

Hi Pharan,

I have found out that if you set animation in inspector to something looping and run the game ( I suppose that inspector animation is setting that animation on track 0 right? ) and then during play time from script you call AddAnimation with delay that first AddAnimation on track 0 does not wait for that delay and fires the animation immediately.

Thank you for the fix in advance. Marek.

Note that a delay > 0 is relative to the when the previous animation started playing, not when AnimationState addAnimation was called (ie when the previous TrackEntry trackTime >= this TrackEntry delay).

A delay of <= 0 is when the previous animation started + the previous animation duration - any mix duration (ie the mix finishes at (0) or before (< 0) the previous animation duration). However, if the previous entry is looping, its next loop completion is used instead of the duration.

Considering the above, do you still see a bug? If your delay is <= 0 it sounds like you found a bug. If your delay > 0 and you wait some time before calling addAnimation, it could be that your delay is too short. You could do something like:

float delay = 0.5f;
TrackEntry entry = animState.getCurrent(0);
if (entry != null) delay += entry.getTrackTime();
animState.addAnimation(0, "run", true, delay);

This would cause "run" to start 0.5 seconds after addAnimation is called.

All clear now. :-) Thank you for the code that explains all.

No problem! We've also improved the API documentation a little.

So we ended with this code :

public static TrackEntry AddAnimation(this AnimationState state, int track, string animation, bool loop, float delay = 0, AddAnimationEnum addAnimationEnum = AddAnimationEnum.FromNow){
            TrackEntry trackEntry = null;
            switch (addAnimationEnum)
            {
                case AddAnimationEnum.SinceLastAnimationStarted:
                    trackEntry = state.AddAnimation(track, animation, loop, delay);
                    break;
                case AddAnimationEnum.FromNow:
                    trackEntry = state.GetCurrent(track);
                    if (trackEntry != null) delay += trackEntry.TrackTime;
                    trackEntry = state.AddAnimation(track, animation, loop, delay);
                    break;
            }
            return trackEntry;
        }

Just to add to it the SinceLastAnimationStarted is likely wrong term and should be called SinceLastQueuedAnimationStartTime.