在做项目的时候。我们经常要用到禁用为灰色的效果。比如 我们要做 图鉴 我们已有的装备物品为彩色。没有的为灰色。
在我们设置UISprite或者UITesture的颜色时。会发现,效果不好还会被图片本身的颜色影响。如下
而我们需要的是这样的效果
这时。就需要我们写Shader来弄了。
Unity中搜索 :Transparent Colored
打开该shader 搜索 函数fixed4 frag (v2f i) : COLOR
{
fixed4 col = tex2D(_MainTex, i.texcoord) * i.color;
return col;
}
将之替换为如下代码fixed4 frag (v2f i) : COLOR
{
fixed4 col;
if (i.color.r < 0.001)
{
col = tex2D(_MainTex, i.texcoord);
float grey = dot(col.rgb, float3(0.299, 0.587, 0.114));
col.rgb = float3(grey, grey, grey);
}
else
{
col = tex2D(_MainTex, i.texcoord) * i.color;
}
return col;
}
另存为。换个名字。然后给UITexture引用就可以了。如下;
当然也可以用脚本动态更改。(传入false则去色)public void SetUITextureColorEnable(UITexture tex, bool enbale)
{
if (tex != null)
{
Debug.LogError("111");
Shader shader = null;
if (enbale == true)
{
shader = Shader.Find("Unlit/Transparent Colored");
}
else
{
shader = Shader.Find("Unlit/Transparent Colored Gray");
}
Debug.LogError(shader.name);
if (tex.shader != shader)
{
tex.shader = shader;
}
}
else
{
Debug.LogError(string.Format("SetUITextureColorEnable tex null/enbale={0}", enbale));
}
}
UISprite的话。需要给图集的材质球更好Shader;
动态的话。如下Material mat = new Material(Shader.Find("Unlit/Transparent Colored Gray"));
atlas.spriteMaterial = mat;
我们可以就一个图集。写一个方法。运行后。将已有的图集动态克隆一份。然后引用新的shader。然后根据条件去取相应的图集。就可了。
修改添加代码。如下:#region 获取图片去色相关
private UIAtlas mHeadIconUIAtlas;
private Material mGrayMaterial;
public void GetGrayIconSprite(UISprite sprite,string spriteName)
{
if (mHeadIconUIAtlas == null)
{
UIAtlas atlas = AssetMgr.GetInstance().GetUIAtlas(AssetType.IconGHead, true);//这里是获取图集。这个根据个人的接口写。用Res.Load 去获取。
mHeadIconUIAtlas = Instantiate(atlas) as UIAtlas;//克隆图集
mGrayMaterial = new Material(Shader.Find("Unlit/Transparent Colored Gray"));//新建材质,并指定Shader
mGrayMaterial.mainTexture = atlas.spriteMaterial.mainTexture;//给材质赋贴图
mHeadIconUIAtlas.spriteMaterial = mGrayMaterial;
}
sprite.atlas = mHeadIconUIAtlas;
sprite.spriteName = spriteName;
}
#endregion
最后。去色Shader下载地址:http://yunpan.cn/csS8MqZbI2kPt 提取码 b8cd
本文链接:
https://bobsong.cn/373.html