BLOG

Notes from the KAYAC hyper-casual team

(Semi-)Automatically Converting What You Made in After Effects for Unity

Takashi Hirayama

I'm Hirayama from the Technology Department, and in this article I'll write about how to play animations made in After Effects in Unity.

The code is published on GitHub almost exactly as it is used in a real product, but please think of it only as a sample. It has many limitations and quirks that only the person who made it understands, and there is no documentation.

What I made

First, please take a look at the video below.

A sample animation converted from After Effects playing in Unity

What a terrible amateur video. This is an animation originally made in After Effects, converted with the tool I'm introducing here so that it runs in Unity. With a couple of conditions ("as long as you only need to play it from start to finish, and it stays within the supported features"), the conversion takes a few minutes. In this example only a few things move, but even with dozens of them, or an epic animation over a minute long, the effort is about the same.

So let me explain why I decided to make this.

Motivation

Please take a look at the following video.

The battle start animation of Tokyo Prison

This is the battle start animation of our game Tokyo Prison. Emblems decorated with flames appear from the left and right, "VS" appears in the middle, three characters on each side who take part in the battle come in from the left and right, a spinning coin appears and decides who goes first, and finally the victory conditions rise up from the bottom.

The question is: how would you make this?

The original material was made by an artist in After Effects. Somehow it has to be brought into Unity.

Are you thinking, "Just have the artist make it in Unity from the start"? True, on some teams that's possible and works well, but on others it doesn't.

Besides, I think that "for art tools, it's better to use whatever feels right in your hands". This is not about learning costs. In the end, much of the cost of game development goes into mass-producing art and animation, and the quality there is critically important. For efficiency too, it seems best for artists to use tools that are comfortable and feel right in their hands: if that's After Effects, After Effects; if it's Flash, Flash. The rest is for programmers to sort out with technology. It depends on the scale of the game, but considering modern production volumes, I think that is often cheaper.

Also, the fact that you can do anything in Unity bothers me a little. There is the problem of conflicts when several people edit a scene, and in smartphone development there is the restriction that you cannot put code into asset bundles, so being able to do too much becomes a source of accidents. There are surely ways of building things that hurt performance or make management harder. In that sense too, the approach of making things in an external tool and then converting them makes it easier to ensure safety. For features you don't want used, you can just say "sorry, that's not supported", and if the converter doubles as a checking tool, it can also give warnings such as "too many objects" or "too large".

Manual or automatic?

When it comes to bringing in things made in another tool, there are broadly two options.

  • Reproduce it by hand in Unity while watching the video
  • Make some nice tool so it can be converted automatically

Each has strengths and weaknesses, so let's sort them out.

The strengths of doing it by hand are the initial cost, flexibility, and performance. You don't need time to build an elaborate mechanism; you can start placing things in the Unity Editor right away. For motion, use whatever you like: Animation, Timeline, DOTween. At first I used DOTween. Partly because my senior colleagues did, but the fact that code can do anything was also a big plus. Unity's old Animation also had a painful restriction where "references break when you change the tree structure", which made it really hard to use. And since programmers should know more about performance than artists, you can expect an implementation that runs faster and takes less space.

The weaknesses are tedium, low fidelity, and fragility when things change. Programmers are usually amateurs at art. Watching a video and thinking "how do I tweak the position, rotation and scale numbers to get the same motion?" is quite hard, and you can't see the subtle differences. Even if, as a programmer, you think "that's about right", to the artist it may be completely wrong, and you may get feedback like "This movement should be more, like, swoosh and then BAM!!" over and over. The work piles up. And this work comes back every time the artist touches the animation. In reality, deadlines and person-hours get in the way, so even if you want to polish it into a cooler motion, that won't be easy. In other words, it is inherently expensive, and the quality also tends to be low.

So what happens if you automate? Simply the opposite.

It has an initial cost, you lose flexibility, and unless it is very well made, performance will be worse than what a programmer would build optimally. In exchange, automatic conversion by a tool solves the fidelity problem, and if conversion is made easy enough, no matter how many times the artist changes things, they can be reflected on the Unity side without much effort.

Now let me introduce the approach I took this time.

Overview of the method

The short answer: it's halfway between manual and automatic.

I made a converter, but I didn't take it to the point where it can do everything. No mask support, no shape support, only linear interpolation for animation, tedious manual work whenever the draw order differs from UGUI: I deliberately left limitations like these in. I was building it in between UI implementation tasks on the team, so I couldn't spend time building those features too.

What the converter produces is code and objects in the scene. Since it is mainly code, flexibility is kept. For example, things like "swap an image dynamically" or "fit another prefab where a certain image is" are easy. Generating Animation assets would probably give better performance, but this time I wanted flexibility, so I went with code. In the video example above too, the character art, where the coin goes, the emblems, the color of the flames and so on are changed dynamically, and this is done simply by adding code.

However, since it is code, it cannot go into asset bundles. That means you cannot add new animations without an app update. In Tokyo Prison, when we want to add something with asset bundles alone, we use Spine. Effects, for example. I would have liked to make data from After Effects loadable from asset bundles too, but there was no time and we couldn't pay the cost of maintaining the tool, so I left that to Spine.

As for fidelity, since the motion is brought over as is, it is reproduced perfectly as long as it stays within the supported features. No matter how complex, how many objects, or how long the animation, the work takes the same effort. The cost of keeping up with the artist's changes is also much lower than with fully manual work.

So let's take a quick look at the workflow.

The actual workflow

Import the library into Unity

Beforehand, put the playback library into Unity. You only need to do this once.

Run the script in After Effects

Let's start converting. Open the After Effects project (it's included in the sample too),

The sample project open in After Effects

and run the prepared script (AfterEffectsToUnityCodeConverter.jsx).

Running the conversion script

When you press "Run" here, it asks for a file name to save to, and when you save, out comes C# code. Here is the file that came out. Import this into Unity.

At this point, change the class name or file name, or add using for namespaces, as needed. As for namespaces, I think it's better to tweak this part of the C# generation script. Also, a class is generated for each composition (After Effects' unit of playback). If the project has several compositions, the code for several classes ends up in one file, so you need to cut out the ones you need (writing multiple files was too much of a hassle).

Import the art into Unity

Import the art you need into the Unity project. Unfortunately, this is manual. In this example I prepared four images: 人.png (person), 背景.png (background), 鳥.png (bird), and ヒット.png (hit).

Create a GameObject in the scene and set up the component

Let's create an instance of this animation in the scene. Create any old GameObject under the Canvas, and attach the script that came out earlier.

The generated script attached to a GameObject

Then set the art in the Inspector. Usually each goes into the slot with the same name, but it depends. This is a hassle and I'd like to do something about it, but things like "use a reduced version for this image only", "this image is already in the game, so use that one", or "this image is a dummy, the real one is this" happen often, so for now it's manual.

Setting the art in the Inspector

Generate the object hierarchy and test playback

Press the "Generate objects" button added by an editor extension. This automatically generates the GameObject hierarchy and Image components with the art set, and the GameObject's name becomes the class name.

The generated object hierarchy

Run it, press the "Initialize" button in the Inspector, then the "Play" button, and it plays. In actual use, though, it's better to make it a prefab. Instantiate it somewhere and call AfterEffectsAnimation.Play(), and it plays.

The converted animation playing in Unity

From there, you edit the code as needed to do whatever else you want. The battle start screen I showed earlier is split into several parts, each made into a prefab, and for text that is replaced dynamically, I modified it by hand to replace the Image with a Text. I'd like to do something about this too.

Implementation

The tool in After Effects

The part that runs in After Effects has to be implemented in JavaScript. If you've never used JavaScript you'll have to learn it, but JavaScript is an easy language "if you just want to write something that runs". Anyone who normally writes C# can do it. If you only ever work in languages with strict type systems like C# or Java, it feels quite different and is fun, so I think it's worth doing to broaden your world.

Note that if you use too-new syntax it won't run in After Effects, so I don't think you need to learn "modern JavaScript". It's more "Classes? What are those?"

As for the API for pulling data out of After Effects, if you read the official documentation and experiment as you go, I think you'll get the feel of it in a day. My sample code may be of help.

On planning the development

Debugging code running in After Effects is hard. So how about splitting it into the part that depends on After Effects and the part that doesn't, and keeping the dependent part as small as possible?

In this implementation, this file with the .jsx extension is the part that only runs in After Effects, and this file with the .js extension is the part that runs elsewhere too.

First, the "part that rips every bit of information out of After Effects and turns it into JSON" can only ever run in After Effects, so that goes in the jsx. Once you have the JSON file, you can run the rest anywhere. I ran and debugged it in Chrome.

I developed this tool on my own initiative (= without counting it as a Scrum task) while UI implementation requests came in every day on the team, so I couldn't get a solid block of time. So I split the development into quite small stages.

  • First, just dumping to JSON. Looking at that, I typed the times and values for DOTween.Sequence's Insert() by hand
    • At this stage the fidelity problem is solved.
  • Prepared a DOTween version of the runtime library
    • This just made it easy to write, with extension methods on Image that let you Insert.
  • Developed just the part that generates DOTween Inserts from the animation in the JSON, running in the browser.
    • At this stage the work of typing things in while looking at the keys disappeared
  • DOTween has speed problems, so I prepared a keyframe animation version of the runtime
    • With DOTween, data is generated every time it plays, so the GC Alloc is terrible.
  • Developed JavaScript that generates C# from the JSON to use this, running in the browser.
  • Prepared a "Generate objects" button with an editor extension
    • The work of reproducing the original tree structure by hand disappeared
  • Integrated the browser part so it all runs in one go in After Effects
    • The JSON dump feature is kept for debugging

That's how it went. I feel that tool development on a team is hard unless each stage makes things easier than before. Even if you stop halfway, it's good to have what you've built so far be usable. Each stage took at most a day to "sort of work", and after that I fixed bugs and added features when I found a moment.

There may also be setups where there are tool-building specialists within the team or across teams, but they can find it hard to meet a team's specific needs, or be slow to respond, so that is not necessarily better.

The Unity side

The Unity-side runtime has the following class structure.

  • AfterEffectsAnimation
    • The base class for animation instances. A MonoBehaviour. Editor extensions such as playback, and callbacks.
  • AfterEffectsInstance
    • Handles the implementation of animation instance playback. Connects GameObjects to the individual keyframe animations and plays them.
  • AfterEffectsResource
    • Data that exists once per animation. A resource, or asset. Holds an AfterEffectsCurveSet.
  • AfterEffectsCurveSet
    • A class that bundles several time series (Curves) of Vector2, float and bool.
  • AfterEffectsCurve
    • Holds the time series of a Vector2, float or bool as an array of keyframes, and returns the value when given a time.

The C# the tool generates is a class derived from AfterEffectsAnimation, and the code that creates the AfterEffectsResource is generated along with it.

public static void CreateResource()
{
    _resource = new AfterEffectsResource(30f);
    _resource
        // layer1_人_png
        .AddPosition(
            "layer1_人_png_position",
            new int[] { 0, 90, 107, 117, 131, 147, 162, 169, 179, 299 },
            new float[] { 52f, 242f, 282f, 308f, 366f, 438f, 474f, 508f, 532f, 678f },
            new float[] { 276f, 294f, 188f, 158f, 148f, 206f, 278f, 246f, 290f, 270f })
        .AddRotation(
            "layer1_人_png_rotation",
            new int[] { 0, 90, 108, 131, 169, 178 },
            new float[] { 20f, 0f, -43f, -12f, 0f, 13f })
        // layer2_鳥_png
        .AddPosition(
            "layer2_鳥_png_position",
            new int[] { 0, 54, 90, 120, 139, 209, 299 },
            new float[] { 660f, 489.861051392424f, 412f, 349f, 205.589212215198f, 115f, 23f },
            new float[] { -20f, 71.5331734089565f, 109f, 120f, 103.796352593026f, 141f, 273f })
        .AddScale(
            "layer2_鳥_png_scale",
            new int[] { 0, 54, 90, 119, 139, 209, 299 },
            new float[] { 10f, 30f, 60f, 100f, 50f, 30f, 10f })
        .AddRotation(
            "layer2_鳥_png_rotation",
            new int[] { 120, 299 },
            new float[] { -18f, 3600f })
        // layer3_ヒット_png
        .AddScale(
            "layer3_ヒット_png_scale",
            new int[] { 120, 121, 125, 132 },
            new float[] { 100f, 200f, 100f, 40f })
        .AddRotation(
            "layer3_ヒット_png_rotation",
            new int[] { 120, 132 },
            new float[] { 26.8260869565217f, 101.8261f })
        .AddOpacity(
            "layer3_ヒット_png_opacity",
            new int[] { 0, 119, 120, 131 },
            new float[] { 0f, 0f, 100f, 0f })
        // layer6_背景ルート
        .AddPosition(
            "layer6_背景ルート_position",
            new int[] { 0, 299 },
            new float[] { 320f, -320f },
            new float[] { 200f, 200f })
        .AddCut("", 0, 300);
}

There's Japanese mixed in, but that's because the After Effects layer names are in Japanese. If you can't stand Japanese in your code, you'll have to get the artists to change how they name things or fix it yourself, but personally I don't think it matters. Unlike the C++ of old, it's Unicode, so there are no bugs caused by character encodings, and it's only auto-generated code anyway, so you rarely maintain it by hand.

Taking layer1_人_png as an example, animation data like "at time 0 x is 52, at time 90 x is 242" is set into the AfterEffectsResource. Since it's code, if you think "let's shift the position", you can just rewrite it here. You can also add an opacity animation on your own.

This defines information like "a node named such-and-such has this kind of position animation", but when playing, you need to know "which GameObject to apply it to". The code for that is generated automatically too.

protected override void InitializeInstance(AfterEffectsInstance instance)
{
    var layer1_人_png_transform = _layer1_人_png.gameObject.GetComponent<RectTransform>();
    var layer2_鳥_png_transform = _layer2_鳥_png.gameObject.GetComponent<RectTransform>();
    var layer3_ヒット_png_transform = _layer3_ヒット_png.gameObject.GetComponent<RectTransform>();

    instance
        // layer1_人_png
        .BindPosition(layer1_人_png_transform, "layer1_人_png_position")
        .BindRotation(layer1_人_png_transform, "layer1_人_png_rotation")
        // layer2_鳥_png
        .BindPosition(layer2_鳥_png_transform, "layer2_鳥_png_position")
        .BindScale(layer2_鳥_png_transform, "layer2_鳥_png_scale")
        .BindRotation(layer2_鳥_png_transform, "layer2_鳥_png_rotation")
        // layer3_ヒット_png
        .BindScale(layer3_ヒット_png_transform, "layer3_ヒット_png_scale")
        .BindRotation(layer3_ヒット_png_transform, "layer3_ヒット_png_rotation")
        .BindOpacity(_layer3_ヒット_png, "layer3_ヒット_png_opacity")
        // layer6_背景ルート
        .BindPosition(_layer6_背景ルート, "layer6_背景ルート_position")
    ;
}

BindXXX is called on an object each playback instance has, called AfterEffectsInstance. The first argument specifies the instance to animate (Transform, CanvasGroup, GameObject, etc.), and the second is the name. This ties the GameObject to the animation data. This is code too, so you can comment out motions you don't need, or add your own.

Implementing Curve

Next comes storing and playing back keyframe data like "4 at time 0, 10 at time 10". AfterEffectsCurve is in charge of this. I made it a struct for no particular reason, but a class would make little difference.

public struct AfterEffectsCurveFloat
{
    private short[] _times;
    private float[] _values;
    public AfterEffectsCurveFloat(
        IList<int> times,
        IList<float> values,
        bool isPercent = false,
        bool removeLeadTime = false)
    {
        Debug.Assert(times.Count == values.Count);
        int timeOffset = (removeLeadTime) ? -times[0] : 0;
        int count = times.Count;
        _times = new short[count];
        _values = new float[count];
        int prevTime = -0x7fffffff;
        for (int i = 0; i < count; i++)
        {
            Debug.Assert((times[i] >= -0x8000) && (times[i] <= 0x7fff));
            Debug.Assert(times[i] >= prevTime, "times must be sorted in ascending");
            _times[i] = (short)(times[i] + timeOffset);
            prevTime = times[i];

            _values[i] = values[i];
        }
        if (isPercent)
        {
            for (int i = 0; i < count; i++)
            {
                _values[i] *= 0.01f;
            }
        }
    }
    public float Get(float time)
    {
        int index = AfterEffectsUtil.FindLargestLessEqual(_times, time);
        float ret;
        if (index < 0)
        {
            ret = _values[0];
        }
        else if (index >= (_times.Length - 1))
        {
            ret = _values[_times.Length - 1];
        }
        else // interpolate
        {
            float t0 = (float)(_times[index]);
            float t1 = (float)(_times[index + 1]);
            float v0 = _values[index];
            float v1 = _values[index + 1];
            float t = (time - t0) / (t1 - t0); //[0, 1]
            ret = ((v1 - v0) * t) + v0;
        }
        return ret;
    }

It simply initializes by putting times and their corresponding values into arrays, and at playback it finds the data with a binary search function called FindLargestLessEqual() and interpolates. For example, if there is data at time 3 and time 7, and the time is 5, it mixes the data at time 3 and time 7 half and half and returns that.

There are a few options for how to build this.

  • Binary search on a sorted array
  • A sorted array, but remember the previous time and scan in order

Binary search on a sorted array needs log N work every time, so whether it's fast is debatable. It does, however, need the least memory for storage. Note that binary search here does not mean "find the data with a certain value", but "find the largest data that is less than or equal to a certain value". In the earlier example there's no data for time 5, so we have to find the 3 just before it. A Dictionary can't be used for this.

Another trick is to remember the previous time and data index, and search from there. When playing in order from the start, most of the time you use the same key or the next one, so the O(log N) work of the binary search is not needed and it becomes O(1).

But there is more data to remember, and unless you add handling like "fall back to binary search when the time jumps more than a certain amount", playback from the middle becomes slow when there are many keys. Partly because, as I said, I couldn't spend much effort on it, I went with a simple binary search. It also helped that I've written this kind of thing several times before, and the performance of the binary search here has never been a problem.

Putting After Effects data into RectTransform

What remains is converting After Effects data such as position, anchor and rotation to match how Unity specifies them. This is in AfterEffectsUtil.Set().

public static void Set(
    RectTransform transform,
    float anchorX = 0f,
    float anchorY = 0f,
    float positionX = 0f,
    float positionY = 0f,
    float scaleX = 100f,
    float scaleY = 100f,
    float rotation = 0f)
{
    // With OnValidate, Awake may not have finished, so this may not be called
    if (transform == null)
    {
        return;
    }
    // Change the origin to the top left
    transform.anchorMax = new Vector2(0f, 1f);
    transform.anchorMin = new Vector2(0f, 1f);
    // Set the reference point
    var size = transform.sizeDelta;
    float pivotX = anchorX / size.x;
    float pivotY = 1f - (anchorY / size.y);
    transform.pivot = new Vector2(pivotX, pivotY);
    transform.anchoredPosition = new Vector2(positionX, -positionY);
    transform.localScale = new Vector3(scaleX * 0.01f, scaleY * 0.01f, 1f);
    transform.localRotation = Quaternion.Euler(new Vector3(0f, 0f, -rotation));
}

In After Effects, scale and opacity are percentages, so they need to be multiplied by 0.01. Also, since the origin is the top left, anchorMax and anchorMin are set too. Furthermore, in After Effects the Y axis points down, so movement in Y needs to be flipped. The rotation angle is reversed too. The most troublesome part is the relationship between After Effects' anchor and RectTransform's pivot. Explaining it would take a while, so please refer to the code above.

What if you want to use SpriteRenderer?

There will be times when you want to use SpriteRenderer instead of UnityEngine.UI. Especially for effects, I think. But this is a pain. Actually, there was a time when it was supported, and the functions are still there, but they probably don't work now.

To reflect After Effects' anchor settings, an extra Transform is needed, so you end up with "two GameObjects per object". It would be easy if I could set a matrix directly on a Unity Transform, but I can't find a way to do that, so for now I've left it as is. In practice, if you go with SpriteRenderer, I feel it's better to take an approach that doesn't create GameObjects at all. You generate a Mesh directly and draw it with a MeshRenderer or similar. That would probably perform better, and it would also be easier when you want to reflect the draw order from After Effects without manual work.

About draw order

In UnityEngine.UI, the draw order is decided by the parent-child relationships. But in After Effects, draw order can be set independently of parent-child relationships. And this tool doesn't take care of that. So if you just move it over as is, the draw order often goes wrong.

I do explain to the artists that "with this parent-child structure in this order, it comes out as is", but as I said earlier, artists should really make things in whatever way is easiest for them, and that's something the programmer should deal with.

But for now, nothing has been done about it. Where the draw order differs, the programmer (that is, me) manually rearranges the parent-child relationships or duplicates GameObjects.

This is probably the biggest problem with this tool right now. To solve it completely, it would probably take one of these:

  • Don't use UnityEngine.UI; specify sort orders with SpriteRenderer
  • Flatten the Transform parent-child relationships, arrange them in draw order, and compute position, rotation and scale myself

With the former, adding UI elements such as buttons later becomes hard. With the latter, modifications like "I'll add a CanvasGroup because I'm adding an opacity animation to everything below this node later" become harder, so extensibility drops, and since the original parent-child structure isn't reflected in the scene, maintainability drops too.

Maybe it would be faster to build an entire UI system, buttons, text and all, on top of SpriteRenderer. If it's made to fit nicely onto the EventSystem and limited to the features the project uses, I feel the implementation cost might not be that high.

Summary

The best solution depends on what you're making, who is making it, and so on, but this time I decided to try the approach of "automating as much as can be done on the side, within the team". There are limitations, such as not being fully automatic and not being able to go into asset bundles, but we've accepted the compromise and are running with it.

On a larger product, however, it wouldn't be acceptable that things can't go into asset bundles, or that the work can't be completed by the artists alone. And on a team with no After Effects users but with Flash users, the data source would be Flash.

For those reasons, I don't expect the tool I published here to be useful as is, but I'd be glad if it serves as a reference for the motivation, planning and design when building this kind of tool.