I suck at Texture2D.ReadPixels

Total noob here, about a month into learning Unity. Making a game in which player basically has a one-shot camera. Can take a screenshot, then view that same screenshot in -game. Using Application.CaptureScreenshot and www.texture was causing huge framerate drop. Plus I’d like to port to iphone eventually.

I’m doing something wrong here. I use a blank texture, then put that texture on a plane…nothing shows up. Any help much appreciated.

var width = 250;
var height = 600;
var tex = new Texture2D( width, height, TextureFormat.RGB24, false );

function Update () {
	if (Input.GetKeyDown("c")){
		// Read screen contents into the texture
 		tex.ReadPixels(Rect(5,250, 250, 600), 0, 0 );
 		tex.Apply();
 	}
}

Try creating the texture in Start instead of field initialization.

// ... omitted code ...
var tex : Texture2D;

function Start() {
	tex = new Texture2D( width, height, TextureFormat.RGB24, false );
}
// ... omitted code ...

You should have gotton an error message similar to this:

ArgumentException: You are not allowed
to call Internal_Create when declaring
a variable. Move it to the line after
without a variable declaration. Don’t
use this function in the constructor
or field initializers, instead move
initialization code to the Awake or
Start function.

I’ve just tested it and it works great:

This is the result after pressing “c” a few times :wink:

ReadPixels

Are you sure that you used your created texture somewhere? I’ve done it like this:

//C#
void Update ()
{
    if (Input.GetKeyDown("c"))
    {
        Texture2D tex = new Texture2D(Screen.width,Screen.height,TextureFormat.RGB24,false);
        tex.ReadPixels(new Rect(0,0,Screen.width,Screen.height),0,0,false);
        tex.Apply();
        if (renderer != null)
           renderer.sharedMaterial.mainTexture = tex;
    }        
}

I’ve recreate the texture everytime since the screen resolution could have changed.

As you can see, after i gathered the image i assign the texture to the renderer that is attached to this gameobject. I attached this script to a plane object which you can see in the screenshot.

This would be the Unityscript version:

//UnityScript
function Update ()
{
    if (Input.GetKeyDown("c"))
    {
        var tex = new Texture2D(Screen.width,Screen.height,TextureFormat.RGB24,false);
        tex.ReadPixels(Rect(0,0,Screen.width,Screen.height),0,0,false);
        tex.Apply();
        if (renderer != null)
           renderer.sharedMaterial.mainTexture = tex;
    }        
}

Hello,

you can use this alternativ, but this code will capture the whole game screen:

Application.CaptureScreenshot("Assets/newImage.png");