Search code examples
c#unity-game-enginedesktop-application

How do I take a screenshot of the current view of my desktop app in Unity using C#?


I have a desktop application that I have made on Unity and I want to take a screenshot of my current view in the application using a C# script attached to the main camera. Please help.

I have browsed other code snippets that I found on this platform and nothing seemed to help.


Solution

  • You can use CaptureScreenshot.

    public class ScreenCapture : MonoBehaviour
    {
        //here you can set the folder you want to use, 
        //IMPORTANT - use "@" before the string, because this is a verbatim string
        //IMPORTANT - the folder must exists
        string pathToYourFile = @"C:\Screenshots\";
        //this is the name of the file
        string fileName = "filename";
        //this is the file type
        string fileType = ".png";
    
        private int CurrentScreenshot { get => PlayerPrefs.GetInt("ScreenShot"); set => PlayerPrefs.SetInt("ScreenShot", value); }
    
        private void Update()
        {
    
            if (Input.GetKeyDown(KeyCode.Space))
            {
                UnityEngine.ScreenCapture.CaptureScreenshot(pathToYourFile + fileName + CurrentScreenshot + fileType);
                CurrentScreenshot++;
            }
        }
    }
    

    A few notes.

    1. I used a verbatim string to define your folder
    2. The folder where you store the screenshot must exist (if you want to create it in the script you can follow this answer)
    3. AFTER COMMENT REQUEST - 1: If you do not set the folder the file will be saved in the default directory of the application (that changes based on the system - you can check it from Application.dataPath)
    4. AFTER COMMENT REQUEST - 2: If you use the same path and filename the file will be overriden, so I added a way to let you save multiple screenshots, also in different sessions using PlayerPrefs.