Search Unity

Graph.Blit won't apply material (I think)

Discussion in 'General Graphics' started by MestreProno, Aug 21, 2021.

  1. MestreProno

    MestreProno

    Joined:
    Jan 18, 2019
    Posts:
    1
    So, this has been stressful, as I couldn't figure out how to do what I want for a whole day... Basically, I want, when my game is paused, to "take a screenshot", blur it and, then, exhibit it as the background for my pause menu! I'm not sure what is the best way to do this, but, after trying (and failing) a lot, I figured I could
    Graphics.Blit
    a texture drawn with
    Texture2D.ReadPixels
    into a
    RenderTexture
    , while, on that
    Blit
    call, passing a material with a shader blur to be applied to the texture. It looks a bit like this in my code:


    Code (CSharp):
    1. public class BgBlur : MonoBehaviour
    2. {
    3.     private RenderTexture renderTx;
    4.     public Material blurMaterial;
    5.     public RawImage img;
    6.  
    7.     private WaitForEndOfFrame frameEnd = new WaitForEndOfFrame();
    8.  
    9.  
    10.     void Start()
    11.     {
    12.         renderTx = new RenderTexture(Screen.width, Screen.height, 0);
    13.         img.texture = renderTx;
    14.     }
    15.  
    16.     void OnEnable() {
    17.         StartCoroutine(BlurBg());
    18.     }
    19.  
    20.     public IEnumerator BlurBg() {
    21.         yield return frameEnd;
    22.  
    23.         var scrnTx = new Texture2D(Screen.width, Screen.height);
    24.         scrnTx.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false);
    25.         scrnTx.Apply();
    26.  
    27.         Graphics.Blit(scrnTx, renderTx, blurMaterial);
    28.        // img.texture = scrnTx;
    29.  
    30.         yield return null;
    31.     }
    32. }

    That
    blurMaterial
    is assigned, via editor, to a material containing only a "Frosted Glass" shader I found on StackOverflow, but I guess it should work, because, when I put it directly on other stuff, via editor, that stuff actually gets blurred.


    I started having doubts about
    Texture2D.ReadPixels
    , wondering if it, really, was reading those pixels, but, upon uncommenting that line below the
    Blit
    call, the image would render, although, obviously, without being blurred, suggesting the problem lies, once again, in the
    Blit
    call (maybe?).


    I'm pretty much desperate at this point, as I've been trying to make this thing work since 1 PM and, now, it's 11:45 PM. HELP!