Hi,
I have been trying to find a way to save a high resolution render texture of the game window to disk at a resolution I specify. I have been experimenting with two code samples from the script reference – each do part of what I want. One is a script that saves a screen shot as a PNG file http://docs.unity3d.com/Documentation/ScriptReference/Texture2D.EncodeToPNG.html and the other is an editor script that saves a PNG file to disk http://docs.unity3d.com/Documentation/ScriptReference/EditorUtility.SaveFilePanel.html.
I tried to combine them with only partial success. I took a section of code from the first script and plugged it into the editor script, trying to make the editor script save a screen shot instead of a selected texture. this script will save the screen shot if I am careful to have nothing selected a the time. If I have, for example, the camera selected I get a screen shot of the camera inspector panel instead of the game window. Also, if I try to capture anything bigger than the current game window, I get an error message, “trying to read pixel out of bounds.”
I also tried to create a render texture and reference it in various ways. I attached it to the camera, but I couldn’t figure out how to reference the camera from inside an editor script.
I also tried to call the static function Apply() (inside the editor script) from an outside function, but couldn’t figure out how to reference that.
I realize I’m in over my head here – never tried to work with and editor script before. My ultimate goal is to be able to render the game window in the resolution and size of my choice for use in compositing. Any help will be greatly appreciated.
Zaffer
// Opens a file selection dialog for a PNG file and saves a selected texture to the file.
import System.IO;
class EditorUtilitySaveFilePanel {
@MenuItem("Examples/Save Texture to file")
static function Apply () {
// 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 ();
//var texture : Texture2D = Selection.activeObject as Texture2D;
var texture : Texture2D = tex;
if (texture == null) {
EditorUtility.DisplayDialog(
"Select Texture",
"You Must Select a Texture first!",
"Ok");
return;
}
var path = EditorUtility.SaveFilePanel(
"Save texture as PNG",
"",
texture.name + ".png",
"png");
if(path.Length != 0) {
// Convert the texture to a format compatible with EncodeToPNG
if(texture.format != TextureFormat.ARGB32 texture.format != TextureFormat.RGB24){
var newTexture = Texture2D(texture.width, texture.height);
newTexture.SetPixels(texture.GetPixels(0),0);
texture = newTexture;
}
var pngData = texture.EncodeToPNG();
if (pngData != null)
File.WriteAllBytes(path, pngData);
}
}
}