- Home /
GrabTexture is always empty
I am using the GrabPass example shader from https://docs.unity3d.com/Manual/SL-GrabPass.html, but it doesn't seem to work. As soon as I turn it on, instead of inverting the background, the sprite disappears, and I don't know where to start to debug why. Am I hooking up the shader wrong?
Here's how it looks if I use the default sprite shader
Here's what happens when I switch to my material that uses the InvertShader
Here's the shader code (I added the _MainTex property to the example because the warnings said it was required for sprite shaders)
Shader "GrabPassInvert"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
// Draw ourselves after all opaque geometry
Tags { "Queue" = "Transparent" }
// Grab the screen behind the object into _BackgroundTexture
GrabPass
{
"_BackgroundTexture"
}
// Render the object with the texture generated above, and invert the colors
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f
{
float4 grabPos : TEXCOORD0;
float4 pos : SV_POSITION;
};
v2f vert(appdata_base v) {
v2f o;
// use UnityObjectToClipPos from UnityCG.cginc to calculate
// the clip-space of the vertex
o.pos = UnityObjectToClipPos(v.vertex);
// use ComputeGrabScreenPos function from UnityCG.cginc
// to get the correct texture coordinate
o.grabPos = ComputeGrabScreenPos(o.pos);
return o;
}
sampler2D _BackgroundTexture;
sampler2D _MainTex;
half4 frag(v2f i) : SV_Target
{
half4 bgcolor = tex2Dproj(_BackgroundTexture, i.grabPos);
return 1 - bgcolor;
}
ENDCG
}
}
}
Answer by Namey5 · Jun 28, 2020 at 09:20 AM
tex2Dproj uses the xyz components of the input sample coordinates - where xy is divided by z to account for projection. In this case however, the perspective scaling factor is actually stored in the w component, so you'll need to swizzle the correct components or perform the division manually;
//Instead of
half4 bgcolor = tex2Dproj (_BackgroundTexture, i.grabPos);
//Try this
half4 bgcolor = tex2Dproj (_BackgroundTexture, i.grabPos.xyw);
//Or this
half4 bgcolor = tex2D (_BackgroundTexture, i.grabPos.xy / i.grabPos.w);
Thanks for your help! It turned out the issue in my case was that my project is using the Universal Render Pipeline, which I guess doesn't support GrabPass?
It does not. I'm surprised this shader works at all - shaders for the new pipelines are written very differently from the built in.
Your answer
![](https://koobas.hobune.stream/wayback/20220613001953im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Shader Problem 0 Answers
perform action on shader compilation/update 0 Answers
Shaders problems after moving to URP 0 Answers
shader problem 0 Answers