shader代码
Shader "UI/UIGrey"
{
Properties
{
[PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
_Color("Tint", Color) = (1,1,1,1)
}
SubShader
{
Tags
{
"Queue" = "Transparent"
"IgnoreProjector" = "True"
"RenderType" = "Transparent"
"PreviewType" = "Plane"
"CanUseSpriteAtlas" = "True"
}
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
float4 color : COLOR;
float2 texcoord : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
float2 texcoord : TEXCOORD0;
float4 worldPosition : TEXCOORD1;
UNITY_VERTEX_OUTPUT_STEREO
};
sampler2D _MainTex;
fixed4 _Color;
v2f vert(appdata_t IN)
{
v2f OUT;
UNITY_SETUP_INSTANCE_ID(IN);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
OUT.worldPosition = IN.vertex;
OUT.vertex = UnityObjectToClipPos(OUT.worldPosition);
OUT.texcoord = IN.texcoord;
OUT.color = IN.color * _Color;
return OUT;
}
fixed4 frag(v2f IN) : SV_Target
{
half4 color = tex2D(_MainTex, IN.texcoord) * IN.color;
fixed3 greyColor = dot(color.rgb, fixed3(0.22, 0.707, 0.071));
color.rgb = greyColor.rgb;
return color;
}
ENDCG
}
}
}
工具类
using UnityEngine;
using UnityEngine.UI;
public class Utils
{
static private Material _uiGreyMat = null;
static private Material uiGreyMat
{
get
{
if (!_uiGreyMat)
{
var shader = Shader.Find("UI/UIGrey");
if (shader)
{
_uiGreyMat = new Material(shader);
_uiGreyMat.hideFlags = HideFlags.HideAndDontSave;
}
}
return _uiGreyMat;
}
}
public static void SetUIDrey(GameObject uiObj, bool isGrey = true)
{
var graphics = uiObj.GetComponentsInChildren<Graphic>();
int length = graphics.Length;
for (int i = 0; i < length; i++)
{
graphics[i].material = isGrey ? uiGreyMat : null;
}
}
}
置灰脚本
using UnityEngine;
using UnityEngine.UI;
public class TestPanel : MonoBehaviour
{
private void Start()
{
//Utils.SetUIDrey(gameObject, false);
Utils.SetUIDrey(gameObject);
}
}
置灰效果