项目需要,参考了一下网上的资料,写了一个shader,给按钮置灰。
shader具体实现如下:
Shader "Transparent Colored Gray"
{
Properties
{
_MainTex ("Base (RGB), Alpha (A)", 2D) = "white" {}
}
SubShader
{
LOD 200
Tags
{
"Queue" = "Transparent"
"IgnoreProjector" = "True"
"RenderType" = "Transparent"
}
Pass
{
Cull Off
Lighting Off
ZWrite Off
Fog { Mode Off }
Offset -1, -1
ColorMask RGB
AlphaTest Greater .01
Blend SrcAlpha OneMinusSrcAlpha
ColorMaterial AmbientAndDiffuse
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _MainTex;
struct appdata_t
{
float4 vertex : POSITION;
half4 color : COLOR;
float2 texcoord : TEXCOORD0;
};
struct v2f
{
float4 vertex : POSITION;
half4 color : COLOR;
float2 texcoord : TEXCOORD0;
};
v2f vert (appdata_t v)
{
v2f o;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
o.color = v.color;
o.texcoord = v.texcoord;
return o;
}
half4 frag (v2f IN) : COLOR
{
// Sample the texture
half4 col = tex2D(_MainTex, IN.texcoord) * IN.color;
float c = 0.299*col.r + 0.587*col.g + 0.184*col.b;
col.r = col.g = col.b = c;
return col;
}
ENDCG
}
}
}
先建一个名为colorGrayMat的材质,把shader文件附加到材质上。
管理material材质代码:
public class MaterialManager
{
public static void addMaterial(Image img, string materialName)
{
Material material = GameAssets.instance.loadMaterial(materialName);
if (img != null && material != null)
{
img.material = material;
}
}
public static void addGrayMaterial(Image img)
{
addMaterial(img,"colorGrayMat");
}
}
调用代码:
MaterialManager.addGrayMaterial(img);
关于shader资料:
官网资料: http://docs.unity3d.com/Manual/SL-SurfaceShaders.html(英文)
http://unity3d.9tech.cn/news/2013/1220/39315.html(中文)
猫都能学会的Unity3D Shader入门指南 http://www.onevcat.com/2013/07/shader-tutorial-1/