0
点赞
收藏
分享

微信扫一扫

Shader(一):UGUI图片置灰


效果

Shader(一):UGUI图片置灰_c#

布局

Shader(一):UGUI图片置灰_shader_02

Shader

Shader "Custom/UIGray"
{
Properties
{
[PerRendererData]_MainTex("MainTex", 2D) = "white" {}
}
SubShader
{
Tags
{
"Queue" = "Transparent"
"IngnoreProjector" = "True"
"RenderType" = "Transparent"
}

Pass
{
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha

CGPROGRAM
#pragma
#pragma

sampler2D _MainTex;
float4 _MainTex_ST; // 纹理无需编辑,可以不配置ST

struct a2v
{
float4 vertex : POSITION;
float4 texcoord : TEXCOORD0;
};

struct v2f
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};

v2f vert(a2v v)
{
v2f f;
f.pos = UnityObjectToClipPos(v.vertex);
f.uv = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;
return f;
}

fixed4 frag(v2f f) : SV_Target
{
// 置灰
fixed3 grayRGB = dot(tex2D(_MainTex, f.uv), fixed3(0.299, 0.587, 0.114));
// 透明度
fixed grayA = tex2D(_MainTex, f.uv).a;
return fixed4(grayRGB, grayA);
}
ENDCG
}
}
FallBack "Diffuse"
}

脚本​​UIGrayScript.cs​

using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class UIGrayScript : MonoBehaviour
{
public bool isGray = true;
private static Material Material => new Material(Shader.Find("Custom/UIGray"));

// 置灰方法
private void SetGray()
{
Image[] images = transform.GetComponentsInChildren<Image>();
foreach (Image image in images)
{
image.material = isGray ? Material : null;
}
}

#if
[CustomEditor(typeof(UIGrayScript))]
private class GrayEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
(target as UIGrayScript)?.SetGray();
}
}
#endif
}


举报

相关推荐

0 条评论