Problem applying 2D texture in script (Solved)

Hello,

I am having some trouble getting a texture and setting it in unity at runtime when using the light weight render pipeline. I want to grab a 2D texture from a camera within my scene and then apply it to a plane within the scene. The capture works fine I think using the following code which is called from a coroutine that waits for the end of the frame.

    RenderTexture renderTexture = myCamera.targetTexture;
                myCamera.Render();
                RenderTexture.active = renderTexture;
                Texture2D renderResult = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false);
                Rect rect = new Rect(0, 0, renderTexture.width, renderTexture.height);
                renderResult.ReadPixels(rect, 0, 0);

If I save the renderResult as a png it works perfectly fine and spits out the right image.

I then try to apply the captured texture to a plane with the following code:

Material planeMaterial = new Material(Shader.Find("LightWeight Render Pipeline/Lit"));
planeMaterial.SetTexture("_BaseMap", renderResult);
renderer.material=planeMaterial;```

I can see that the material is applied in the editor during runtime but the plane just turns grey and the basemap box in the editor is filled with a solid white. 

Does anyone have any idea what could be going wrong here?

Nevermind I figured it out on my own. Apparently you still need to use a Texture2D.Apply() even when using ReadPixels. Adding the line
renderResult.Apply();
After the ReadPixels command fixes the problem

1 Like

If all you’re doing is looking to copy a render texture into a texture2D to be used as a material’s texture, why not just use the render texture itself?

If you’re reusing the render texture for multiple things, then I’d suggest using Graphics.CopyTexture() instead. ReadPixels() copies data from the GPU to the CPU, then Apply() copies it back. CopyTexture() does the copy on the GPU skipping the expensive steps of copying the data between the CPU and GPU.

2 Likes