I thought I would find an answer somewhere instantly but apparently not. So here it goes:
I need to convert a RenderTexture to a 1D array for each frame update in the script (C#) in Unity. How can I do that?
That is it actually. The rest is kind of besides the point of the question, but let me also explain why I need to do this anyway: ..so that I can then dump the 1D array within a cell of a row in a .csv file. I would collect data (including the rendered texture data) at each frame update and write all this collected per-frame data using WriteLine(line). My idea is that this would save me from wasting computation time that would otherwise be spent encoding images and saving those images as separate files with each update.
CodePudding user response:
The RenderTexture, and the underlying Texture, objects don't have a lot to work with in this regard. So the idea is to record the data in the RenderTexture as a new Texture2D, and use that new item to read the data you're looking for.
Here's a piece of code that should read a 1D array of type Color32 struct (untested):
public Color32 [ ] GetRenderTexturePixels ( RenderTexture renderTexture )
{
var texture = new Texture2D( renderTexture.width, renderTexture.height, TextureFormat.RGB24, false );
// record the current render texture.
var currentRenderTexture = RenderTexture.active;
// Set the new render texture.
RenderTexture.active = renderTexture;
texture.ReadPixels ( new Rect ( 0, 0, renderTexture.width, renderTexture.height ), 0, 0 );
texture.Apply ( );
// reapply the previous render texture.
RenderTexture.active = currentRenderTexture;
// Return then texture2d pixels. This assumes mipmap level 0.
return texture.GetPixels32 ( );
}