做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<UISprite>().color; bgColor.r = 0; item.FindChild(itemName + "/bgImage").GetComponent<UISprite>().color = bgColor;
目前又發現一個新的問題:UIScroll沒有裁切圖片,造成邊緣顯示出來,還在找解決辦法!