I have a shader for images with "wonky" colors - the reason the colors are so messy is because it's a sneaky way to encode data into the RGB color channels eg the red channel is terrain data the blue channel is water data and the green channel is lighting data (highlights & shadows).

I have color bars for each set of data eg I take the value for the red channel and find it's position on the color bar and that is the proper color to return for the pixel.

Red Channel Data from original image

Red Channel form Image

Color bar for Red Channel Data

Color bar for Red Channel

So that this point, as I'm looking at every pixel via my fragment shader, red values of 1 will pull from the color bar to the furthest right side (lighter colors) while values of 0 will pull from the color bar on the furthest left side (darker colors).

I have a basic fragment shader setup where I can get the respective color values from the image (main texture) and can read out the rgb values of each frag. I also have my color bar pulled into the shader via sampler2D but I'm not sure how to sample a color from the color bar based only the red value from the main tex's red value.


Knowing the 0-1 value of red at every pixel on my mian texture, how can I return the associated color from the color bar?


basics of my shader

    _ColorBar("Color Bar", 2D) = "" {}

    // Cull off // for doublesized texture @jkr todo: disable for prod
    Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
    ZWrite Off
    // ZTest Off
    Blend SrcAlpha OneMinusSrcAlpha
    // Cull front 
    // LOD 100

    Pass {

        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"


        sampler2D _MainTex; // maintex is set programatically at runtime
        sampler2D _ColorBar; // set via the unity inspector

        float4 frag(v2f f) : COLOR
            fixed4 col = tex2D(_MainTex, f.uv);
            return col;
FallBack "VertexLit"

Inspector View

Unity Inspector View


1 Answer 1


To sample _ColorBar based on the 0-1 value of the _MainTex's red channel, you can just use the sampled value's red channel as UV input to the tex2D function for the _ColorBar, like this:

fixed4 frag (v2f i) : SV_Target
     // sample the _MainTex at the uvs
     fixed4 color_from_map = tex2D(_MainTex, i.uv);

     // Sample the _ColorBar at the 0-1 red channel value of the color_from_map
     fixed4 sampled_color = tex2D(_ColorBar, color_from_map.r);
     return sampled_color;
  • \$\begingroup\$ works like a charm \$\endgroup\$
    – Jacksonkr
    Commented Feb 11, 2022 at 15:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .