做Unity开发过程中,有需求让未开启的功能模块的入口灰色显示。因为没有滤镜的概念,所以没flash那么方便。解决思路还是Shader,以前按网上其他帖子的方法,一直没有成功实现过。这两天比较闲一点,专门研究了下,总算成功了。
NGUI里已经有Unlit - Transparent Colored.shader。一般打Atlas的时候默认就是这个。如下图。
fixed4 frag (v2f IN) : COLOR { return tex2D(_MainTex, IN.texcoord) * IN.color; } ENDCG
上面就是Transparent Colored.shader内的核心颜色渲染代码,可见是没有灰色转换的功能的。我们这里需要使用另外个shader,也是NGUI自带的:Unlit - Transparent Colored Gray.shader,它的核心代码如下:
fixed4 frag (v2f IN) : COLOR
{
fixed4 col;
if (IN.color.r < 0.001)
{
col = tex2D(_MainTex, IN.texcoord);
float grey = dot(col.rgb, float3(0.299, 0.587, 0.114));
col.rgb = float3(grey, grey, grey);
}
else
{
col = tex2D(_MainTex, IN.texcoord) * IN.color;
}
return col;
}
当颜色值的r值为0的时候,就灰色显示。
图集打好后,我们看看效果:
我们将r设置为0,但是图片还是没有成灰色,这是为何呢?后来根据http://bbs.9ria.com/thread-431562-1-1.html的启示,找到NGUI,UIDrawCall.cs类,发现如果是Scroll下,NGUI会更改默认shader,我们是Unlit - Transparent Colored Gray.shader,它会去寻找Unlit - Transparent Colored Gray (SoftClip).shader,然后没找到就默认回nlit - Transparent Colored .shader,这下好办了,我们复制一份Unlit - Transparent Colored Gray.shader,更改它的名字为Unlit - Transparent Colored Gray.shader,然后打开它的代码:
Shader "Unlit/Transparent Colored Gray"
{
Properties
{
_MainTex ("Base (RGB), Alpha (A)", 2D) = "black" {}
}
将最顶上一行修改下名字:
Shader "Unlit/Transparent Colored Gray (SoftClip)"
{
Properties
{
_MainTex ("Base (RGB), Alpha (A)", 2D) = "black" {}
}
然后回过头来再看看显示:
灰色显示成功。
我们要代码控制它灰色怎么操作呢?
Color bgColor = item.FindChild(itemName +"/bgImage").GetComponent().color; bgColor.r = 0; item.FindChild(itemName + "/bgImage").GetComponent ().color = bgColor;
目前又发现一个新的问题:UIScroll没有裁切图片,造成边缘显示出来,还在找解决办法!