- Home /
Faster way to get raw texture data than Texture2D.ReadPixels?
I want to capture the screen the user is seen and send that data as a byte array to a remote machine, running another Unity3D application.
I am using Texture2D.GetRawTextureData() at present, but after timing it, I see that it takes up to 12 milliseconds:
private byte[] FrameData;
public IEnumerator SetFrame()
{
// Can take up to 12 ms!
yield return new WaitForEndOfFrame();
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
Debug.Log(sw.ElapsedMilliseconds.ToString());
FrameData = tex.GetRawTextureData();
Destroy(tex);
}
On this other machine, I do the following to display the image to the user:
void DisplayFrame(byte[] frame)
{
//3ms at most
Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
texture.LoadRawTextureData(frame);
texture.Apply();
GetComponent<Renderer>().material.mainTexture = texture;
}
Is there something faster than ReadPixels?
(PS how the hell do I insert a new line between sentences? This editor just ignores them!)
I’m away from my desktop, but I will look into this question more in depth when back.
However, is your problem ReadPixels() or GetRawTextureData()? In your code sample, you only test the speed of ReadPixels() but your question is referring to GetRawTextureData()?
Answer by Elarm00 · Mar 09, 2018 at 02:59 PM
If you are working on 2018 you could use ( or try at least, as its still experimental ) AsyncGPUReadback.Request, also take a look at this https://medium.com/google-developers/real-time-image-capture-in-unity-458de1364a4c basically what you want to do is find a place where triggering gpu flush is the least expensive. Good Luck!
Thanks, I'll look into AsyncGPUReadback.Request
. I've come across that link you posted a while back, but it didn't really help me because I didn't know what they were talking about with "if the garbage collector is thread safe, maybe we can run it on a background thread and avoid blocking the main render thread.".
P.S you have included a ,
at they end of your link. You need to remove it, otherwise it goes to a 404 webpage.
Your answer
Follow this Question
Related Questions
What is the bottleneck in this iphone code? 3 Answers
ReadPixels works on device (iPad) but not in the editor? 3 Answers
Read-Write enabled sprite cant use sprite packer. 0 Answers
ReadPixels is capturing GUI, how to get a screencap without GUI 1 Answer
Why is ReadPixels on my RenderTexture creating a pure gray texture? 1 Answer