Someone has done before, but the efficiency is not high: http://blog.csdn.net/onerain88/article/details/12197277
His code:
Fixed4 frag (v2f I): Color
{
Fixed4 Col;
If (I. color. r <0.001)
{
Col = tex2d (_ maintex, I. texcoord );
Float gray = dot (Col. RGB, float3 (0.299, 0.587, 0.114 ));
Col. RGB = float3 (Gray, gray, gray );
}
Else
{
Col = tex2d (_ maintex, I. texcoord) * I. color;
}
Return Col;
}
After modification, the efficiency is significantly improved:
Struct v2f
{
Float4 vertex: sv_position;
Half2 texcoord: texcoord0;
Fixed4 color: color;
Fixed Gray: texcoord1;
};
Sampler2d _ maintex;
Float4 _ maintex_st;
V2f Vert (appdata_t V)
{
V2f O;
O. vertex = MUL (unity_matrix_mvp, V. vertex );
O. texcoord = transform_tex (V. texcoord, _ maintex );
O. Color = V. color;
O. Gray = dot (V. Color, fixed4 (1, 1, 1, 0 ));
Return O;
}
Fixed4 frag (v2f I): Color
{
Fixed4 Col;
If (I. Gray = 0)
{
Col = tex2d (_ maintex, I. texcoord );
Col. RGB = dot (Col. RGB, fixed3 (. 222,. 707,. 071 ));
}
Else
{
Col = tex2d (_ maintex, I. texcoord) * I. color;
}
Return Col;
} Set uisprite. Color = color. Black.
The principle is to apply for a register texcoord1 in v2f to place the data gray, and calculate whether it is gray in the vertex program Vert. In fragment program frag, use I. Gray = 0 for if judgment.
The reason for the low efficiency of the first code is that if (I. color. r <0.001) Here we access the color component R, but it is clearly stated in the official documentation that this is inefficient unless necessary.
In addition, in PC (fixed Gray: texcoord1;), you can change it to (bool Gray: texcoord1;), but there are problems in mobile devices (Android and IOS.
Reset version (reproduced)