using UnityEngine;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class UIGray : MonoBehaviour {
private bool _isGray = false;
public bool isGray
{
get { return _isGray; }
set
{
if (_isGray != value)
{
_isGray = value;
SetGray(_isGray);
}
}
}
static private Material _defaultGrayMaterial;
static private Material grayMaterial
{
get
{
if (_defaultGrayMaterial == null)
{
_defaultGrayMaterial = new Material(Shader.Find("UI/MyGray"));
}
return _defaultGrayMaterial;
}
}
public void SetGray(bool isGray)
{
Image[] images = transform.GetComponentsInChildren<Image>();
for (int i = 0; i < images.Length; i++)
{
Image g = images[i];
if (isGray)
{
g.material = grayMaterial;
}
else
{
g.material = null;
}
}
}
#if UNITY_EDITOR //提供编辑器预览
[CustomEditor(typeof(UIGray))]
public class UIGrayInspector : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
UIGray gray = target as UIGray;
gray.isGray = GUILayout.Toggle(gray.isGray, "Is Gray");
if (GUI.changed)
{
EditorUtility.SetDirty(target);
}
}
}
#endif
}
Shader "UI/MyGray"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
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;
};
sampler2D _MainTex;
float4 _MainTex_ST;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
float gray = dot(col.xyz, float3(0.299, 0.587, 0.114));
col.xyz = float3(gray, gray, gray);
return col;
}
ENDCG
}
}
}
