Using Coroutines to Control Animation in Unity

August 12, 2019

Coroutines for Animation Timings

Unity

Youtube - Coroutines and Animation: Beyond Beginner Unity Tutorials
By: Tom coAdjoint

For a Unity project, I needed to control the flow of my program to process an animation fully before moving on to the next operations. Timing concerns normally lead me to coroutines, so I looked into controlling animations with coroutines in Unity.

The approach I ended up using for a quick fix solution was just to use WaitForSeconds in Unity. I basically just had the operation start the animation and then WaitForSeconds approximately the duration of the animation (which needs to be hard coded in at this point), and then continue with operation. While this works, it feels a bit clunky and hard to work with. For example, changing out the animation will require changing the time accordingly every time. Also different animations will need different values entered individually.

I came across this tutorial linked above which seemed promising for a better animation timer, especially for game building purposes. Unfortunately, I don't have a lot of experience programming animation related objects in Unity, so I was not able to fully grasp how this setup worked. I need to look into the already available methods and variables Unity provides when working with the Animator and Animation more.

The main coroutine driving everything here is IEnumerator WaitForAnimation, which has the following setup:

IEnumerator WaitForAnimation(string name, float ratio, bool play)
{
var anim = animation[name];

if(play) animation.Play(name);

while(anim.normalizedTime + float.Epsilon + Time.deltaTime < ratio)
yield return new WaitForEndOfFrame();
}

The overall premise makes sense. You input an animation name, a ratio of how much of the animation you want to play, and a bool to activate it. It was unclear which variables were created by the tutorial and which exist in Unity already. animation[name] appears to be an array reference, but I am unsure if this is how Unity normally deals with animations or if this was created separately. normzlizedTime is also new to me, but that does appear to be a built in time of animation reference.

It will take a bit more researching, but this approach definitely seems to be more general and useful if I can determine exactly how it works.

Comments

Popular posts from this blog

Online Multiplayer Networking Solution Tutorial Using Unity and Mirror - Tutorial by: Jason Weimann

Sebastian Lague A* Tutorial Series - Path Smoothing - Pt. 08 and Pt. 09

Designing Pixel Art Color Palettes in Aseprite by AdamCYounis