I am trying to setup a system for utilizing uvs to tile a texture and reduce draw calls. I'm using Unity. I create a texture which records the x index of the tile from a tileset into the red channel and try to use it in the shader. Here's the shader code:
sampler2D _TilemapTex;
sampler2D _MainTex;
float _MaxIndex;
vector _TilesetDim;
vector _TilemapDim;
struct vertexInput {
float4 vertex : POSITION;
float2 texcoord: TEXCOORD0;
};
struct vertexOutput {
float4 pos : SV_POSITION;
float2 texcoord: TEXCOORD0;
};
vertexOutput vert(vertexInput v)
{
vertexOutput output;
output.pos = UnityObjectToClipPos(v.vertex);
output.texcoord = v.texcoord;
return output;
}
float4 SampleMap(float2 texcoord) {
return tex2D(_TilemapTex, texcoord).r * 255;
}
float4 GetUv(int index, float2 texcoord) {
int xpos = index;
int ypos = _TilesetDim.y - 1;
float2 uv = float2(xpos/_TilesetDim.x, ypos);
float xoffset = frac(texcoord.x * _TilemapDim.x) / _TilesetDim.x;
float yoffset = frac(texcoord.y * _TilemapDim.y) / _TilesetDim.y;
uv += float2(xoffset, yoffset);
float4 main = tex2D(_MainTex, uv);
return main;
}
float4 frag(vertexOutput i) : SV_Target
{
int index = tex2D(_TilemapTex, i.texcoord).r * 255;
return GetUv(index, i.texcoord);
}`
I'm a beginner with shaders so maybe I'm missing something simple. Here's the result:

It looks interesting but I expected it to fill entire tiles.