由于人眼对RGB敏刚程度不同,对绿色的敏感度最高,对红色的敏感度次之,对蓝色的敏感度最低,因此需要对RGB设置不同的权重,来达到灰度显示的效果,比较常用的RGB权重值为 R:0.298912, G:0.586611,B: 0.114478
grayColor.rgb = float3(color.r0.298912 , color.g0.586611 ,color.b*0.114478)
1 UI对象不可用的时候显示置灰效果
通过shader进行控制置灰,shader中添加变量 _ShowGray,在代码中可以通过动态给改变量赋值的方式,控制是否进行置灰显示
shader 代码是通过 Image Effect shader进行简单修改得到的,
- Shader "UI/UIGray"
- {
- Properties
- {
- _MainTex ("Texture", 2D) = "white" {}
- [Toggle]_ShowGray("show gray", Range(0,1)) = 0
- }
- SubShader
- {
- // No culling or depth
- Cull Off ZWrite Off ZTest Always
- //-----add code-------
- Blend SrcAlpha OneMinusSrcAlpha
- //----finish----
- Pass
- {
- CGPROGRAM
- #pragma vertex vert
- #pragma fragment frag
-
- #include "UnityCG.cginc"
-
- struct appdata
- {
- float4 vertex : POSITION;
- float2 uv : TEXCOORD0;
- };
-
- struct v2f
- {
- float2 uv : TEXCOORD0;
- float4 vertex : SV_POSITION;
- };
-
- v2f vert (appdata v)
- {
- v2f o;
- o.vertex = UnityObjectToClipPos(v.vertex);
- o.uv = v.uv;
- return o;
- }
-
- sampler2D _MainTex;
- fixed _ShowGray;
-
- fixed4 frag (v2f i) : SV_Target
- {
- fixed4 col = tex2D(_MainTex, i.uv);
- // just invert the colors
- //col.rgb = 1 - col.rgb;
- //----add code----
- fixed gray = dot(col.rgb, float3(0.298912, 0.586611, 0.114478));
- col.rgb = lerp(col.rgb, fixed3(gray, gray, gray), _ShowGray);
- //-----finish-----
- return col;
- }
- ENDCG
- }
- }
- }
-
2 场景中所有对象置灰,比如战斗失败时候显示的置灰效果
场景置灰,一般采用的是对相机渲染进行设置,在相机上面添加脚本,在OnRenderImage回调方法里面,对渲染对象进行处理
脚本
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class PostEffectGray : MonoBehaviour
- {
- public Material grayMaterial;
- void OnRenderImage(RenderTexture src, RenderTexture dest)
- {
- Graphics.Blit(src, dest, grayMaterial);
- }
- }
-
-
启用置灰脚本

禁用置灰脚本

这里的Gray材质球用的的shader是一个简单的置灰效果shader,代码如下
- Shader "Unlit/Gray"
- {
- Properties
- {
- _MainTex ("Texture", 2D) = "white" {}
- }
- SubShader
- {
- Tags { "RenderType"="Opaque" }
- LOD 100
-
- Pass
- {
- CGPROGRAM
- #pragma vertex vert
- #pragma fragment frag
- // make fog work
- #pragma multi_compile_fog
-
- #include "UnityCG.cginc"
-
- struct appdata
- {
- float4 vertex : POSITION;
- float2 uv : TEXCOORD0;
- };
-
- struct v2f
- {
- float2 uv : TEXCOORD0;
- UNITY_FOG_COORDS(1)
- float4 vertex : SV_POSITION;
- };
-
- sampler2D _MainTex;
- float4 _MainTex_ST;
-
- v2f vert (appdata v)
- {
- v2f o;
- o.vertex = UnityObjectToClipPos(v.vertex);
- o.uv = TRANSFORM_TEX(v.uv, _MainTex);
- UNITY_TRANSFER_FOG(o,o.vertex);
- return o;
- }
-
- fixed4 frag (v2f i) : SV_Target
- {
- // sample the texture
- fixed4 col = tex2D(_MainTex, i.uv);
- half3 gray = dot(col.rgb, half3 (0.22, 0.707, 0.071));
- // apply fog
- UNITY_APPLY_FOG(i.fogCoord, col);
- return fixed4(gray.rgb, col.a);
- }
- ENDCG
- }
- }
- }
-
到此这篇关于unity置灰处理的实现的文章就介绍到这了,更多相关unity置灰处理内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!