Breaking ReadPixels() in pieces

I want to be able to call the method ReadPixels() without freezing the screen.

My guess is that ReadPixels() is a big for that loops through the Rect it receives as parameter.

My idea is: put ReadPixels() in a coroutine and break the big for in a lot of small fors, like this:

BEFORE

 //this is what I guess original ReadPixels() is like
ReadPixels(Rect r){
    for(int row = ...){
        for(int col = ...){
            //reading pixel (row,col)
        }
    }
}

AFTER

//here is the way I want to implement
IEnumerator FastReadPixels(Rect r){
    for each row {
        ReadPixels( new Rect with only this row and all columns)
        yield return null;
    }
}

Is this possible?

I’m assuming you’re referring to Texture2D.ReadPixels:

In which case, sure, you can use ‘GetPixel’ to read a single pixel:

With that you can loop row by row, col by col, and call GetPixel at whatever pace you’d like.

So:

Sure, it’s possible.

1 Like

My intention is to read the pixels from the screen, therefore the ReadPixels().

Will GetPixel() work the same way? I thought GetPixel would return a pixel from the texture, not from the screen. Am I wrong?

Note I said:

I linked to Texture2D.ReadPixels.

Which ‘ReadPixels’ are you talking about?

I’m talking exactly about the ReadPixels you linked.

My understanding is that a Texture2D is just a rectangle of pixels, and when I call ReadPixels I set the texture’s pixels to match the screen pixels (within the rect I pass as argument).

I thought that GetPixel would just return a pixel from the Texture2D (and not from the screen!), but am I wrong? What does GetPixel really gets? Screen pixel or Texture2D pixel? My goal is to get the screen pixels into the texture breaking the big operation in small operations so that it wont be too slow.

Sorry, I misinterpreted your original post.

You’re trying to screencap a region of the screen.

No, using a coroutine won’t really help with you there since a Coroutine really just lets you perform work over a series of frames. So the screen would be changing through out that time.

What is it you’re actually trying to accomplish. Not the how you’re doing it (ReadPixels), but why you’re doing it, your end goal.

My end goal is to capture a region of the screen, just as you said.

An extra point: I don’t care if the screen changes during the time the screenshot takes, that’s why I wanted to do it in a coroutine, my main goal is to avoid the lag ReadPixels() causes.

Why not just render your screen to a render texture and then read from that?

1 Like

because I’m using a library whose function gets a texture2D as a parameter.

hmm. I assumed there would be an easy-straight forward way to pull a Texture2D from a RenderTexture, but I guess there is not. Here is some example code from the API documentation:

It’s also using ReadPixels, though, so you’re back to square one. :frowning: