I found a tutorial that does this in a surface shader but I want to learn how to do it in a fragment shader.
I’m creating some meshes procedurally and combining them into one and I am setting the “slice” in the texture 2D array as the Z in the UVs like so.
Vector3[] uv = new Vector3[] { new(0,0,3), new(0,1,3), new(1,1,3), new(1,0,3) };
So in the above there the 3 is the slice I want to use for that mesh.
And in my shader I’m not really sure how to use that.
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float4 uv : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
float4 uv : TEXCOORD0;
};
v2f vert(appdata d)
{
v2f o;
o.vertex = UnityObjectToClipPos(d.vertex);
o.uv = d.uv;
return o;
}
UNITY_DECLARE_TEX2DARRAY(_Texture);
fixed4 frag(v2f i) : SV_Target
{
return UNITY_SAMPLE_TEX2DARRAY(_Texture, i.uv);
}
ENDCG
Here is an example of how to do it in a surface shader.
CGPROGRAM
#pragma surface surf Standard vertex:vert
UNITY_DECLARE_TEX2DARRAY(_Tx);
struct Input
{
float2 uv_MainTex;
float arrayIndex;
};
void vert(inout appdata_full v, out Input o)
{
o.uv_MainTex = v.texcoord.xy;
o.arrayIndex = v.texcoord.z;
}
void surf(Input IN, inout SurfaceOutputStandard o)
{
fixed4 c = UNITY_SAMPLE_TEX2DARRAY(_Texture, float3(IN.uv_MainTex, IN.arrayIndex));
o.Albedo = c.rgb;
}
ENDCG