Can I sample pixels from the screen w/o a RenderTexture?

I’d like to be able to sample the rgb values of pixels at various points on the screen.
The only way I can see to do this is by rendering the camera to a texture, sampling from that texture and pointing a second camera at a plane with the RenderTexture on it so everything shows up on screen. That seems like a really, really inefficient way of doing it though, plus I’m not sure about casting between a Texture and a Texture2D (so I can sample)… or managing coordinates between the screen and the RenderTexture.

You could use the Texture2D.ReadPixels method.

Right, that’s the function I was planning on using - but does the screen present itself anywhere to be sampled directly?

yes in the render texture if you render to it with Unity Pro
otherwise you can only grab it from the backbuffer through readpixels

How do I access the backbuffer? It doesn’t seem to be mentioned in the documentation.

Oops; you’re right, I got it. ReadPixels reads from the screen unless you tell it otherwise. I was ignoring it because I only wanted one pixel. This works:

private var myTex = Texture2D(1, 1);

function Sample( x : int, y : int ) : Color
{
	myTex.ReadPixels(Rect(x, y, 1, 1), 0, 0);
	var c = myTex.GetPixel(0, 0);
	Debug.Log(String.Format("rgb is {0} {1} {2}", 255*c.r, 255*c.g, 255*c.b) );
        return c;
}

Is there anyway though to do ReadPixels or ReadPixel from a RenderTexture? this only seems to work on Texture2D.
I’d like to render out a png from a RenderTexture, what’s the best way of doing it?

make the rendertexture the currently active one on your camera and then use readpixels, that way you can sample it to a texture2d which you then can encode to png

there used to be a rendertexture based “capture screenshot” functionality which does exactly this basically

Nice, I actually just figured it out from another post you’ve made in another thread :slight_smile:
That works great!
thanks.

The way I understand it, ReadPixels() only works in Unity Pro, right?
(can’t check for myself right now)

Is there anyway to do this in the free version ?
(this = “Can I sample pixels from the screen w/o a RenderTexture?”)

No, ReadPixels works on free and Pro.

RenderTextures on the other hand are Pro only, so if you are on the free Unity, you can only use ReadPixels to read from the current backbuffer (what you see in the game window)

Oh, great
I’ll test it later
thanks for the help