Exporting Unity frames as Animated GIFs - Sat, Feb 13, 2016
Recently I discovered a Unity-compatible library that allows exporting Unity textures into animated GIFs. This library is extremely easy to use and platform independent. It is called GifEncoder
, which is based on NGif
, an older C# based project for encoding GIFs.
To use it, just copy the GifEncoder
folder to your Assets directory, point a camera at what you would like to record, and in each frame send the pixels from the camera’s render target to the encoder:
public void Update()
{
renderCamera.Render();
RenderTexture.active = renderTexture;
var frameTexture = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGB24, false);
frameTexture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
gifEncoder.AddFrame(frameTexture);
UnityEngine.Object.Destroy(frameTexture);
}
In this example, renderCamera
is a public field, and the camera should be assigned to it, renderTexture
is a temporary RenderTexture
that the camera renders into, and gifEncoder
is the encoder object. These are initialized as below:
public void Start()
{
renderTexture = new RenderTexture(800, 480, 24); //GIF Resolution
renderCamera.enabled = false;
renderCamera.targetTexture = renderTexture;
gifEncoder = new AnimatedGifEncoder(@"C:\Gifs\MyGif.gif");
gifEncoder.SetDelay(1000 / 30);
}