Turning GIFs to spritesheets IN UNITY

So GIFs don’t work in unity. The work around that gets posted often is convert it into a spritesheet, and while that is very easy to do on the internet, for the sake of my program I need to convert it within unity itself. For example, I want it to be possible to save a GIF to unity in the files and then have unity automatically convert it into a spritesheet and give it back. Can anyone explain how to do this?

Well GIF is a quite old format and what you probably think about are animated gifs. Though the animation capability are actually an extension and it’s even interpreted differently depending on the parser. GIF itself contains several frames which are simply applied on top of each other and a frame could even just be a “diff” frame. GIF essentially represents a virtual canvas and contains “drawing instructions” which are applied one after the other. The animation extension simply allows to add a delay between such operations.

There are some GIF loaders out there, but most of them are not free. I’ve written a GIF loader from scratch, however it’s still essentially “work in progress” for quite some time now since I hadn’t much time or interest in polishing the code. However it should work with most GIF files. It essentially just parses all the blocks in the file. You can use the various DrawTo methods of the image or one of the rendering blocks in order to draw it into a Color32 array which can be used to create a texture in Unity.

I just added the “DrawImageTo” method which allows you to reconstruct a certain frame and draw it into a Color32 array at a certain offset. This method will apply all frames in order up to the specifed frame. “DrawPartialFrameTo” only draws a single frame into the color array. Depending on the type of gif this may work. However usually a frame requires the previous frames.

It’s up to you how you arrange them into a texture atlas. The size of the image can be read from the “screen” property.

Here’s a simple example that draws all the frames into a horizontal strip of images:

    GIFLoader loader = new GIFLoader();
    GifImage image = loader.Load(pathToYourImageFile);
    Texture2D tex = new Texture2D(image.screen.width * image.imageData.Count, image.screen.height);
    var colors = tex.GetPixels32();
    for(int i = 0; i < image.imageData.Count; i++)
        image.DrawImageTo(i, colors, tex.width, tex.height, image.screen.width * i, 0);

If you encounter any issues, feel free to open an issue on the github page. Though please test with other images before you open an issue. If possible provide a sample image that doesn’t work / produces errors.