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:
Here is my 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 <4; i++){
if(factor >= positions[i] && factor <positions[i+1]){
fixed localFactor = (factor - positions[i])/(positions[i+1] - positions[i]);
outColor = lerp(colors[i], colors[i+1], localFactor);
}else if (factor > positions [_NumColors-1]){
outColor = colors[_NumColors -1];
}
}
return outColor;
}
It works. But it sucks, for a few reasons:
- the number of colors in the ramp are hardcoded. Adding a list of them in the Unity editor would be far better.
- if/else statements. I understand that these are terrible for performance and are to be avoided.
- the array of colors is declared in the function, which means a new array has to be created for every fragment (I think).
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?