title: color ramp shader (cg / shaderlab)
body: <p>I have a shader function which functions like the "color ramp" node in Blender3D. It takes as input a float between zero and one and outputs a color that is a blend of any number of colors in a specified order:</p>
  
  <p>blender3D color ramp<br/><a href="https://i.stack.imgur.com/FTiM3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FTiM3.png" alt="blender3D color ramp"></a></p>
  
  <p>Here is my code:</p>
  
  <pre><code>fixed4 ColorRamp(float factor){
              float positions[5] = {_Pos0, _Pos1, _Pos2, _Pos3, _Pos4}; 
              fixed4 colors[5] = {_Color0, _Color1, _Color2, _Color3, _Color4}; 
  
              fixed4 outColor = _Color0;
  
              for(int i = 0; i &lt;4; i++){
  
                  if(factor &gt;= positions[i] &amp;&amp; factor &lt;positions[i+1]){
                      fixed localFactor = (factor - positions[i])/(positions[i+1] - positions[i]);
                      outColor =  lerp(colors[i], colors[i+1], localFactor);
                  }else if (factor &gt; positions [_NumColors-1]){
                      outColor = colors[_NumColors -1];
                  }
              }
              return outColor;
          }
  </code></pre>
  
  <p>It works. But it sucks, for a few reasons:</p>
  
  <ol>
  <li>the number of colors in the ramp are hardcoded. Adding a list of them in the Unity editor would be far better.</li>
  <li>if/else statements. I understand that these are terrible for performance and are to be avoided.</li>
  <li>the array of colors is declared in the function, which means a new array has to be created for every fragment (I think). </li>
  </ol>
  
  <p>My main question is the first one: How can I change the number of colors in the ramp without having to edit a hardcoded value?</p>