How to take a screenshot in Unity

You can always take screenshot using the print screen option or 3rd party tools like the snipping tool in Windows. But what if you can take the screenshot of only the game view in Unity? In this tutorial, we will see how to take the screenshot of your game view using code and save it as a PNG file in your assets folder.

You can check out our post on Unity recorder if you want to record your gameplay.

  1. Create a new empty game object called “take_screenshot”.
  2. Add a new script to it and call it “png_save_script”.

Let’s try to understand the code

We will use two new functions here. The first one is WaitForEndofFrame and the second one is ScreenCapture.CaptureScreenshot. WaitofEndOfFrame is used to wait for all objects in the scene to load before taking the screenshot using ScreenCapture.

Free Unity asset banner

You need to use a coroutine for this purpose as WaitForEndofFrame returns an IEnumerator. If you are not sure on how this work read our post on Unity Coroutine.

Here is our Coroutine code

IEnumerator screenshot()
    {
        yield return new WaitForEndOfFrame();

         ScreenCapture.CaptureScreenshot("test.png");
            
        }
    }

This will save a PNG file of name test in the projet folder. Lets try and create a new folder and save the file in that.

IEnumerator screenshot()
    {
        yield return new WaitForEndOfFrame();
        
            if (!System.IO.Directory.Exists("Assets/Animation")
            {
             System.IO.Directory.CreateDirectory("Assets/Animation");
            }
            ScreenCapture.CaptureScreenshot("Assets/Animation/test.png");
            
        }
    }

Now that you know how to take a screenshot and save it in a specific folder. The next step is to start the coroutine

This part is simple. You just need to type in a single line of code

StartCoroutine(screenshot());

Here is the final script for your reference. This will take a screenshot whenever enter is pressed.

public class png_save_script : MonoBehaviour
{
    
    IEnumerator screenshot()
    {
        yield return new WaitForEndOfFrame();
        
            if (!System.IO.Directory.Exists("Assets/Animation")
            {
             System.IO.Directory.CreateDirectory("Assets/Animation");
            }
            ScreenCapture.CaptureScreenshot("Assets/Animation/test.png");
            
        }
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Return))
        {
           StartCoroutine(screenshot());
        }
        
        
        
    }
}

Here is a screenshot of the 3D model I took in Unity.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.