unity黑白滤镜_Unity NGUI图片去色黑白效果

在Unity中,通过自定义Shader实现图片去色效果,用于创建如图鉴中彩色和灰色物品显示。文章介绍了如何修改'Unlit/Transparent Colored' Shader实现灰度效果,并提供了一个动态改变UITexture和UISprite颜色状态的方法。此外,还分享了去色Shader的下载链接和代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在做项目的时候。我们经常要用到禁用为灰色的效果。比如 我们要做 图鉴 我们已有的装备物品为彩色。没有的为灰色。

在我们设置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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值