Honestly, I still haven’t fully understanded how scroll view works, but I ended up creating two shaders, one for the texture and one for the scroll view. Using the stencil buffer, I managed to draw only the pixels that were within the scroll view with my custom shader (material with custom shader) setted.
Looking up into the documentation, it’s said that the scrollview works setting the stencil buffer to 1, but even checking the 1 on the stencil buffer, without a specific materials set on the scrollview, it doesn’t actually detect nothing and just draw.
For anyone who’s interested, here it is how my two shaders look like:
This check the stencil buffer and draw only if it finds a 1 in the buffer (and mask the texture using the alpha of a different one)
Shader "Custom/StencilEqualOne" {
Properties{
_Stencil("Stencil ID", Float) = 0
_MainTex("Texture", 2D) = "white" {}
_AlphaMask("Mask texture", 2D) = "white" {}
}
SubShader{
Tags{
"Queue" = "Transparent"
"RenderType" = "Transparent"
}
LOD 200
Lighting Off
ZWrite Off
ZTest Off
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
Stencil {
Ref 1
Comp equal
Pass keep
}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct Input {
float4 vertex : POSITION;
fixed4 color : COLOR;
half2 texcoord : TEXCOORD0;
};
struct v2f {
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
half2 texcoord : TEXCOORD0;
float4 worldPosition : TEXCOORD1;
};
sampler2D _MainTex;
sampler2D _AlphaMask;
v2f vert(Input IN) {
v2f o;
o.worldPosition = IN.vertex;
o.vertex = mul(UNITY_MATRIX_MVP, o.worldPosition);
o.texcoord = IN.texcoord;
o.color = IN.color;
return o;
}
fixed4 frag(v2f IN) : SV_Target {
fixed4 col = tex2D(_MainTex, IN.texcoord);
col.a *= tex2D(_AlphaMask, IN.texcoord).a;
clip (col.a - 0.001);
return col;
}
ENDCG
}
}
Fallback "Diffuse"
}
This one set the stencil buffer to 1 (applied to the scrollview) and draw a texture as background
Shader "Custom/StencilMaskOne" {
Properties{
_MainTex("Texture", 2D) = "white" {}
}
SubShader{
Tags{
"Queue" = "Transparent"
"IgnoreProjector"="True"
"RenderType"="Transparent"
"PreviewType"="Plane"
"CanUseSpriteAtlas"="True"
}
//ColorMask 0
ZWrite off
Lighting Off
Blend SrcAlpha OneMinusSrcAlpha
Stencil {
Ref 1
Comp always
Pass Replace
}
Pass {
Cull Off
ZWrite On
ZTest Less
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct appdata {
float4 vertex : POSITION;
fixed4 color : COLOR;
half2 texcoord : TEXCOORD0;
};
struct v2f
{
float4 pos : SV_POSITION;
fixed4 color : COLOR;
half2 texcoord : TEXCOORD0;
float4 worldPosition : TEXCOORD1;
};
v2f vert (appdata v) {
v2f o;
o.worldPosition = v.vertex;
o.pos = mul(UNITY_MATRIX_MVP, o.worldPosition);
o.texcoord = v.texcoord;
o.color = v.color;
return o;
}
sampler2D _MainTex;
half4 frag(v2f i) : COLOR {
half4 col = tex2D(_MainTex, i.texcoord) * i.color;
return col;
}
ENDCG
}
}
}
I’m a newcomer when it comes to shader programming, so there could be some errors within my shaders, but in my case they’re working flawlessly