Unity Texture, Texture2D, RenderTexture

posted in: Non classé | 0

In Unity, I get struggle some times to figure out what’s the difference between Texture, Texture2D and RenderTexture.

In simple words

  • Texture represent the GPU (graphic card memory) side of a Texture
  • RenderTexture, based on Texture, add the shader/material management
  • Texture2D, based on Texture, add a CPU (processor, ram) side management. It handle the Hard Drive loading/saving of the pnj/jpg/etc

 

Note: Texture2D.Apply pass CPU data to the GPU

Example code. Use it as a toolbox

/// Pass a GPU RenderTexture to CPU Texture2D
/// This opperation has heavy cost (ReadPixels)
/// We reduice the RenderTexture size first to be more efficient
 
void RenderTextureToTexture2D()
{
 
	// Please, be power of 2 for performance issue (2, 4, 8, ...)
	int downSize = 2;
 
	RenderTexture textureToDownsizeAndCopyToCPU = new RenderTexture(1920, 1080, 0);
	Texture2D newTexture2DToBeLoadedTo = new Texture2D(textureToDownsizeAndCopyToCPU.width / downSize, textureToDownsizeAndCopyToCPU.height / downSize, TextureFormat.ARGB32, false);
 
	// Load textureToDownsizeAndCopyToCPU from something you like...
 
	// Create a temporary downsized texture
	RenderTexture textureDownsized = RenderTexture.GetTemporary(textureToDownsizeAndCopyToCPU.width / downSize, textureToDownsizeAndCopyToCPU.height / downSize);
 
	// Remember currently active render texture
	RenderTexture currentActiveRT = RenderTexture.active;
 
	RenderTexture.active = textureDownsized;
 
	// Copy textureToDownsizeAndCopyToCPU to textureDownsized
	Graphics.Blit(textureToDownsizeAndCopyToCPU, textureDownsized);
 
	// Read the RenderTexture image into it
	// Pass GPU bytes to CPU
        // Very performance consuming
	newTexture2DToBeLoadedTo.ReadPixels(new Rect(0, 0, textureDownsized.width, textureDownsized.height), 0, 0, false);
	// Debug.Log(tex2D.width + " " + tex2D.height);
	// Restorie previously active render texture
	RenderTexture.active = currentActiveRT;
 
	RenderTexture.ReleaseTemporary(textureDownsized);
}
 
 
void RenderTextureFromShader()
{
        Graphics.Blit(null, RenderTextureDestination, materialShader);
}

 

And here comes the Link party to Unity Doc for more precise information

Texture

RenderTexture

Texture2D

Leave a Reply