Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

RenderTexture black after recreating it

Discussion in 'Scripting' started by illegallyblonde, Feb 19, 2021.

  1. illegallyblonde

    illegallyblonde

    Joined:
    Aug 22, 2015
    Posts:
    6
    I have a RenderTexture which is the target texture for a Camera I've set up on the scene.

    They work fine, but the RenderTexture quality is dependent on its width and height, so I want to make sure the width and height match the size of the screen.

    I saw this trick on several forums:

    Code (CSharp):
    1. if (otherCamera.targetTexture != null)
    2. {
    3.     otherCamera.targetTexture.Release();
    4. }
    5.  
    6. otherCamera.targetTexture = new RenderTexture(Screen.width, Screen.height, 24);
    7. otherMeshRenderer.material.mainTexture = otherCamera.targetTexture;
    8.  
    9. otherCamera.Render();
    However, after I tried it, the render texture is black. Any idea why that would happen?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,780
    If you play and press pause (or execute Debug.Break in the above code) and look at that camera you used for the snapshot, what does that camera see in the little editor inset editor window?
     
  3. illegallyblonde

    illegallyblonde

    Joined:
    Aug 22, 2015
    Posts:
    6
    The camera preview correctly shows the scene. This is likely something about the render texture
     
  4. illegallyblonde

    illegallyblonde

    Joined:
    Aug 22, 2015
    Posts:
    6
    I figured it out, the problem was in this line:

    otherMeshRenderer.material.mainTexture = otherCamera.targetTexture;


    Since I've created a custom shader for this, which the material uses, this isn't the correct way to set the material texture. My shader accepts the texture as an argument, so the fix was to pass it like so:

    otherMeshRenderer.material.SetTexture("MyTexture", otherCamera.targetTexture);
     
    Kurt-Dekker likes this.