Unievrsity of Games University of Games

Animation scripting in Unity Engine

I don’t need to explain anybody what is animation, right? We can bring to life almost every static object in the game with animations. Good fit of animations makes game better and more vivid.

Photo by Fonsi Fernández / Unsplash

Animation scripting in Unity Engine

I don’t need to explain anybody what is animation, right? We can bring to life almost every static object in the game with animations. Good fit of animations makes game better and more vivid.

Why animation are good for your game?

At start I think, I don’t need to explain anybody what is animation, right? We can bring to life almost every static object in the game with animations. Good fit of animations makes game better and more vivid. Although a lot of game developers don’t animate user interface in their productions. It’s such a pity, because with even small effort we can reach great results. Today, I would like to show you how create some animations using one simple method.

Classic approach of animations

In Unity, we have 2 (two) built-in components to cope with animations: Animation and Animator. First of them allow create simple animations with key frames and animation curves. According to this keys, we can manipulate features of various objects: position, scale, color etc. Animator component is a controller of animations. With this tool we can control flow of animation. Work with this components may seem tedious, because we must perform tons of clicks to get final results. A lot of programmers skip this stage complaining that “It’s not my cup of tea” or “Too much time” etc. Good information for you — there is more programmers using the friendly way to create animations. Thanks for beloved scripts :).

Scripting approach to animation

I tried search phrase “Scripting animation” into Google. And you know what? Main results are about “How to control Unity Animator component by script”. It’s not really helpful for us. Still we must create a classic animation, setup key frames and workflow in Animator. Our goal is animate gameobject using only scripting. Scripting animation has one important advantage — is very universal. We can simply attach script to gameobject with animated features and everything works well. This way we can create scripts for our UI: buttons, pop-ups etc. Inside script we describe when animation will execute, for example: on mouse enter. Sounds great, right? Where are disadvantages, you may ask. At the beginning it will seem complicate. Don’t be afraid, we will show you how to do it.

Coroutines, blessing or pure evil?

Animation to proper working needs to wait certain period of time between frames. Sure, we can create primitive animations in Update() function but it is not comfortable. What if we wish execute animation within certain method? For example click animation, when player clicks the button.

public void OnPointerDown(PointerEventData eventData)  
{   
        float step = 0.5f;  
        float value = 5;  
        do  
        {  
            transform.position -= Vector3.up \* step;  
            value -= step;  
        }  
        while (value > 0);  
}

In theory, loop should move button down — it will look like pressed button. But only in theory — in practice we notice that button teleported into final position immediately. Why? The answer is simple — entire loop executes in one frame. The next question is — how to wait at least one frame between every iteration of while loop? Coroutines gives us a hand. It is a IEnumerator type method which allow us wait certain period of time between instructions. In this instance, method Click() will look like this:

IEnumerator Click()  
{   
        float step = 0.5f;  
        float value = 5;  
        do  
        {  
            transform.position -= Vector3.up \* step;  
            value -= step;  
            yield return null;  
        }  
        while (value > 0);  
}

We should pay attention at new instruction:

yield return null;

This instruction force coroutine to wait for the end of frame to perform next line. What if we hold longer, for example 1 second? We need to use WaitForSeconds class object:

yield return new WaitForSeconds(1);

How to run IEnumerator method is not obvious. We can’t just write Click(), to start coroutine. We have to use this function:

StartCoroutine(Click());

At first glance it looks super easy. What therefore is a coroutines problem? A lot of coroutines make program flow less obvious to read. What is more using a lot of IEnumerator can cause stack memory issues and increase usage of CPU. In spite of that coroutines are still better way to create animations than bool spaghetti in Update() method. So the question is can we do it in another way?

Magic of tweeners

First time when I saw in one plugin this instruction:

HOTween.To(myObject, 1, "fieldName", 2);

didn’t understood how it’s possible that there is no coroutines but gameobject is animated with one line of code. It interested me a lot so I decided start my little investigation. And I discovered a group of plugins called tweeners. Most popular tween plugins on the market:

  • HOTween
  • DOTween (HOTween successor)
  • iTween
  • Tween
  • UITween

Above tweeners are totally free. So you can use it without any problems in your projects. In University of Games we especially like this one: DOTween by Demigiant (http://dotween.demigiant.com). It is very easy to implement and use. You only need to copy package into project and then in Tools/Demigiant/DOTween Utility Panel click Setup DOTween. Voilà! If we want use DOTween in our script at first we need to add this using:

using DG.Tweening

DOTween with extension methods shortcut allow use operations directly on gameobject. For the instance our _Click()_method:

transform.DOMoveY(transform.position.y - 5, 0.5f);

It’s everything, really! Simple, right? Button will change position by 5 units during half a second. With tweener we can animate components like:

  • AudioSource
  • Camera
  • Light
  • Rigidbody
  • Transform
  • UI elements
  • and more…

The big advantage of using tweeners is more clean code and better performance than in coroutines. I created a simple test to compare DOTween with IEnumerator method. In this test I animated simultaneously 10 000 cubes.

Unity Profiler

As you see at profiler’s screens IEnumerator has more CPU usage than tweeners. And what is important coroutine highly used CPU in every frame.

Conclusion

Coroutines and tweeners is really interesting alternative comparing to Unity standard animations. If you are a programmer and you don’t like play with animation frames and curves. Animation scripting is great solution for you. Surely UI with simple animations has better feeling than static one.

To help us create more free stuff, consider leaving a donation through Patreon where you can vote for the next asset pack and get access to future packs & articles earlier. Sharing knowledge is our passion. Unfortunately, keeping a team of professionals costs a lot that’s why we are constantly taking on new opportunities.

​We’ll be publishing any news on the following outlets:

Thanks for reading!

Leszek W. Król

Leszek W. Król

On a daily basis, I accompany companies and institutions in designing strategies and developing new products and services.