Unity 3D Game Engine – Get Screenshot – Desktop

How to get a in-game Screenshot with Unity 3D

Method 1

Application.CaptureScreenshot

NOTICE: CaptureScreenshot is asynchronous. This is because capturing and saving the screen can take awhile.

Inside Hierarchy create a structure with:

1. Some Objects

2. Main Camera, attach the script ‘GetScreenShot.js’

GetScreenShot.js


#pragma strict

function Start() {
}

function OnGUI()
{
  if (GUI.Button(Rect(10,10,200,50),"Capture Screenshot"))
  { 
    print (Application. persistentDataPath);
    //static function CaptureScreenshot(filename: string, superSize: int = 0): void;
    Application.CaptureScreenshot("Pictures/Screenshot.png");
  }
}


To test it, inside your Project folder create the subfolder /Pictures

Play it, you will find yourProjectFolder/Pictures/Screenshot.png

The console will print: ‘C:/Users/yourusername/AppData/LocalLow/DefaultCompany/Touch_Move’ on Win 7

You can Use persistentDataPath.
The Application.persistentDataPath is different for various platforms (iOS vs Android), and is the /Documents directory, a read-write path where you can put your downloaded stuff

Use the code:


#pragma strict

function Start() {
}

function OnGUI()
{
  if (GUI.Button(Rect(10,10,200,50),"Capture Screenshot"))
  { 
    print (Application. persistentDataPath);
    //static function CaptureScreenshot(filename: string, superSize: int = 0): void;
    Application.CaptureScreenshot(Application.persistentDataPath+"/Frame.png");
  }
}

It will save the image into:
C:/Users/yourusername/AppData/LocalLow/DefaultCompany/Touch_Move/Frame.png

See also:

Method 2

Texture2D.EncodeToPNG

Reference: http://docs.unity3d.com/Documentation/ScriptReference/Texture2D.EncodeToPNG.html

Encodes this texture into PNG format.


        // Saves screenshot as PNG file.
	import System.IO;
	// Take a shot immediately
	function Start () {
		UploadPNG ();
	}
	function UploadPNG () {
		// We should only read the screen buffer after rendering is complete
		yield WaitForEndOfFrame();
		// Create a texture the size of the screen, RGB24 format
		var width = Screen.width;
		var height = Screen.height;
		var tex = new Texture2D (width, height, TextureFormat.RGB24, false);
		// Read screen contents into the texture
		tex.ReadPixels (Rect(0, 0, width, height), 0, 0);
		tex.Apply ();
		// Encode texture into PNG
		var bytes = tex.EncodeToPNG();
		Destroy (tex);
		// For testing purposes, also write to a file in the project folder
		// File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);

		// Create a Web Form
		var form = new WWWForm();
		form.AddField("frameCount", Time.frameCount.ToString());
		form.AddBinaryData("fileUpload",bytes);
		// Upload to a cgi script
		var w = WWW("http:/localhostcgi-bin/env.cgi?post", form);
		yield w;
		if (w.error != null) {
			print(w.error);
		} else {
			print("Finished Uploading Screenshot");
		}
	}