Search code examples
c#unity-game-enginepngscreenshot

How can i update an image on runtime in unity?


I'm buidling a smooth transtion from a level scene to a menu scene. The idea is to make a screenshot of the level just before the next scene(menu) loads. then take this screenshot which overlays the entire screen and will fade out to reveal the menu.

At the end of a level I take a screen shot.

ScreenCapture.CaptureScreenshot("Resources/DestroyedBoss.png");

When I load the next scene this screenshot should load and overlay the entire scene.

     public Texture2D myTexture;

 void Start()
 {

     // load texture from resource folder
     myTexture = Resources.Load("DestroyedBoss") as Texture2D;

     GameObject rawImage = GameObject.Find("RawImage");
     rawImage.GetComponent<RawImage>().texture = myTexture;
 }

The screenshot will fade and the object containing it will be destroyed.

     public RawImage imageToFade;

 void Update()
 {
     imageToFade.color -= new Color(0, 0, 0, 0.2f * Time.deltaTime);

     if (imageToFade.color.a < 0.1) 
         Destroy(this.gameObject);
 }

This all works fine, except for loading of the screenshot itself.

It would seem that unity does not update the image while running the game. And always uses the screenshot from the previous time I ran the game.

I have been searching/googling and trying for 2 days now and I am at a loss.

How can I make this work? Is there a way to update the png file while running my game? Maybe create a temp container for the screenshot and set this to the RawImage?


Solution

  • Like derHugo commented. you can use Application.persistentDataPath to save your image.

    ScreenCapture.CaptureScreenshot(Application.persistentDataPath+"DestroyedBoss.png");
    

    For loading the image, you can use UnityWebRequestTexture.GetTexture.

     IEnumerator SetImage()
    {
        yield return new WaitForSeconds(1);
    
        using (UnityWebRequest uwr =
            UnityWebRequestTexture.GetTexture(Application.persistentDataPath + "DestroyedBoss.png"))
        {
            yield return uwr.SendWebRequest();
    
            if (uwr.isNetworkError || uwr.isHttpError)
            {
                Debug.Log(uwr.error);
            }
            else
            {
                // Get downloaded asset bundle
                myTexture = DownloadHandlerTexture.GetContent(uwr);
    
                GameObject rawImage = GameObject.Find("RawImage");
                rawImage.GetComponent<RawImage>().texture = myTexture;
                FadeOut.instance.StartFade();
            }
        }
    }
    

    It works ok, but it takes a few seconds for the screenshot to appear in the folder. So for me... it does not work great. I'll be using another technique. Instead of fading the screenshot while loading the menu. I'll stop the game, (Time.timescale = 0) and fade in a screenshot of the menu, then load the actual menu scene.

    Thanks again derHugo.