private IMegacoolPreviewFrame loadNextFrame(IMegacoolPreviewData preview)
 {
     for (int i = 0; i < preview.GetNumberOfFrames(); i++)
     {
         IMegacoolPreviewFrame frame = preview.GetNextFrame();
         if (frame == null)
         {
             Debug.Log("Skipping preview frame that failed to load");
             continue;
         }
         return(frame);
     }
     return(null);
 }
    private IEnumerator PreviewMegacoolGif()
    {
        previewTexture = new Texture2D(2, 2, TextureFormat.ARGB32, false);

        IMegacoolPreviewFrame nextFrame = loadNextFrame(previewData);

        if (nextFrame == null)
        {
            Debug.Log("Could not load any frames in preview");
            yield break;
        }
        bool isFirstFrame = true;

        int    currentFrameTargetTimeMs = nextFrame.GetDelayMs();
        double currentFrameTimeMs       = currentFrameTargetTimeMs - Time.deltaTime * 1000;

        // The preview is stopped in StopPreview by stopping the coroutine
        while (true)
        {
            if (nextFrame == null)
            {
                Debug.Log("Couldn't load next frame in preview, skipping");
                yield return(null);

                nextFrame = loadNextFrame(previewData);
                continue;
            }

            currentFrameTimeMs += Time.deltaTime * 1000;
            if (currentFrameTimeMs < currentFrameTargetTimeMs)
            {
                yield return(null);

                continue;
            }

            bool loadSuccess = nextFrame.LoadToTexture(previewTexture);
            nextFrame.Release();
            if (!loadSuccess)
            {
                yield return(null);

                nextFrame = loadNextFrame(previewData);
                continue;
            }

            guiSystem.SetTexture(previewTexture);

            if (isFirstFrame)
            {
                isFirstFrame = false;
                guiSystem.ShowPreview();
            }

            currentFrameTimeMs       = currentFrameTimeMs - currentFrameTargetTimeMs;
            currentFrameTargetTimeMs = nextFrame.GetDelayMs();

            yield return(null);

            nextFrame = loadNextFrame(previewData);
        }
    }