How do I properly use Coroutines, yield and animators to sequence commands ?

I’m having a hard time understanding how yield works inside coroutines.

I’m using a coroutine to start a series of animators in a certain sequence.

When I use waitForSeconds in between animator.play commands, this works as I would expect… however, when I want to wait when an animator has finished, and then execute the next command, it does not work.

In my example below, the last command (loadScene2) should only be fired after the animator (scene1-ufos) has finished, but instead it is fired at the same time as my last animator.play command.

What am I doing wrong here ?

    IEnumerator startMikeAnimation()
    {
        animatorMikeDigging.Play("scene1-mikefadein");
        animatorMikeDirt.Play("scene1-mikedirt");
        yield return new WaitForSeconds(5);
        animatorVondsten.Play("scene1-vondsten");
        yield return new WaitForSeconds(5);
        animatorUfos.Play("scene1-ufos");


        while (animatorUfos.GetCurrentAnimatorStateInfo(0).normalizedTime < 1.0f)
        {
            yield return null;
        }

        StartCoroutine(loadScene2());
    }

Hi Swanne, in the end it was a really noob error on my end. I was keeping in using the "EventSystem.current.SetSelectedGameObject(button);" inside the for loop that was adding the answer to the canvas, instead of outside the loop -_-. Now it works properly. The issue with accessing the Color Tint transitions still remains, but in the end it was an error by me. Thanks!

2 Answers

2

yield return null; - returns nothing - and I’m pretty sure it just breaks the while loop

animatorUfos.Play("scene1-ufos");
yield return new WaitForSeconds(animatorUfos.GetCurrentAnimatorStateInfo(0).length - 0.01f);

should do the trick - I subtract the 0.01f - since I was using it for a short not really looping anim and would sometimes see it loop back to the first frame(object pooled explosion) - your mileage may vary

Hey @Serotonina Oh no ha ha Well at least you found it the problem and you'll learn from that. Great work, well done! Have fun finishing your game and thank you for letting me know :)

Many thanks for that snippet… this looks like a cleaner way to achieve what I am trying, but sadly, it does not work in my case…

It seems that when I play a “state” called “scene1-ufos” from my Animator animatorUfos, that this clip does not reflect my currentAnimatorState… Is that possible ?

I think that my empty “New State” is always seen as the currentState, but I’m not sure.

There’s no way to debug.log the currentstate name, and I can’t find a way to programmatically set the current state.

My animator is set up like this, I have added an empty new state to make sure this animation does not start automatically. I think I’m doing this wrong.

This is all awfully complicated for the simple 2D animations I’m trying to trigger.