2
\$\begingroup\$

I have a screenshot preview at the end of the game's level. When I am loading the screenshot, it makes the game freeze for a moment. What may I do so there would be no freeze when I am loading that screenshot? Here is myc ode:

private IEnumerator ShowScreeshotPreview()
        {
    screenshotTexture = new Texture2D(Screen.height, Screen.height, TextureFormat.RGB24, false);
            for (int i = 0; i < 9; i++)
            {
                yield return null;
            }
            RenderTexture.active = Singletons.Get<SpecialEffectsHelper>().MainCharacterScript.GetComponent<GeneratorScript>().screenshotTexture;
            screenshotTexture.ReadPixels(new Rect(0, 0, Screen.height, Screen.height), 0, 0);
    screenshotTexture.Apply();
            RenderTexture.active = null; //Added to avoid errors

            screenshotPrview.mainTexture = screenshotTexture;
    ScreenshotPreviewAnimator.SetBool("visible", true);
            screenshotLoaded = true;

            yield return null;
        }
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

You can't do anything to prevent the freeze. The Texture2D.Apply() method is expensive. The larger the texture dimensions, the longer the freeze.

You can't manipulate Unity objects, such as GameObject or Texture2D, in a separate thread. In some cases, you can prepare the data on another thread, to be used by or with the Unity objects in the UI thread. However, in your case, it won't help; you have to call Texture2D.Apply() in the UI thread.

\$\endgroup\$
0
\$\begingroup\$

The solution is not to prevent the freeze, but to force it to happen at some earlier time when it will not be as noticeable to the user.

I suggest having a loading screen during which you call that up for the first time, to display for a single frame, invisibly. This will force the load at that point. The load screen may have a spinner or whatever that would be expected to periodically pause, so the user will tolerate any pauses at this point. Then, by the time you call it in-game, everything will look normal as there will now be no freeze.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .