Hello, everyone!
I am really new to shaders, but I am trying to write a custom shader for a game I am working on. I am modifying Unity’s Sprites/Default shader and what I want the shader to do is:
• get two sprite textures, tint one of them with the Sprite Renderer tint color and then add both textures.
Like this:
I am tinting the bottom sprite (white shirt) with red and adding it to the upper sprite (character). Both textures are PerRendererData and I am setting them by code using MaterialPropertyBlock.
This is all working right. The problem is that when I put these textures inside an Atlas, the shader don’t work anymore.
It looks like this:
I believe that the problem is that the shader is usign the same texcoord to both sampler2D. This works on the first case because both textures have the same texcoord, but not on the second one, when they are different (because they are on different parts of the Atlas). But I don’t know how to get the different texcoord in the shader.
My current shader code:
Shader "Custom/SpriteColor"
{
Properties
{
[PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
[PerRendererData] _SecondTex ("Sprite Texture", 2D) = "white" {}
[MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
}
SubShader
{
Tags
{
"Queue"="Transparent"
"IgnoreProjector"="True"
"RenderType"="Transparent"
"PreviewType"="Plane"
"CanUseSpriteAtlas"="True"
}
Cull Off
Lighting Off
ZWrite Off
Blend One OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile _ PIXELSNAP_ON
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
float4 color : COLOR;
float2 texcoord : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
half2 texcoord : TEXCOORD0;
};
v2f vert(appdata_t IN)
{
v2f OUT;
OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
OUT.texcoord = IN.texcoord;
OUT.color = IN.color;
#ifdef PIXELSNAP_ON
OUT.vertex = UnityPixelSnap (OUT.vertex);
#endif
return OUT;
}
sampler2D _MainTex;
sampler2D _SecondTex;
fixed4 frag(v2f IN) : SV_Target
{
fixed4 c = tex2D(_MainTex, IN.texcoord);
fixed4 s = tex2D(_SecondTex, IN.texcoord) * IN.color;
s.rgb *= s.a;
c.rgb *= c.a;
return c + s;
}
ENDCG
}
}
}
I need both textures to be on the same shader so that I have the resultant sprite on a single layer. I don’t want to use two sprites, one above the other on different layers.
Maybe I am doing it all wrong and someone may have a better idea. I will gladly accept it.
Thanks!