新建一个名为firstShader的Shader,选择Standard Surface Shader,双击打开,可以看到如下脚本:
Shader “Custom/firstShader” {
Properties {
_Color (“Color”, Color) = (1,1,1,1)
_MainTex (“Albedo (RGB)”, 2D) = “white” {}
_Glossiness (“Smoothness”, Range(0,1)) = 0.5
_Metallic (“Metallic”, Range(0,1)) = 0.0
}
SubShader {
Tags { “RenderType”=”Opaque” }
LOD 200
CGPROGRAM
// Physically based Standard lighting model, and enable shadows on all light types
#pragma surface surf Standard fullforwardshadows
// Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0
sampler2D \_MainTex;
struct Input {
float2 uv\_MainTex;
};
half \_Glossiness;
half \_Metallic;
fixed4 \_Color;
// Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
// See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
// #pragma instancing\_options assumeuniformscaling
UNITY\_INSTANCING\_CBUFFER\_START(Props)
// put more per-instance properties here
UNITY\_INSTANCING\_CBUFFER\_END
void surf (Input IN, inout SurfaceOutputStandard o) {
// Albedo comes from a texture tinted by color
fixed4 c = tex2D (\_MainTex, IN.uv\_MainTex) \* \_Color;
o.Albedo = c.rgb;
// Metallic and smoothness come from slider variables
o.Metallic = \_Metallic;
o.Smoothness = \_Glossiness;
o.Alpha = c.a;
}
ENDCG
}
FallBack "Diffuse"
}
借助上面的代码构造可以看出Shader的基本结构: Shader “——–” Properties { Subshader { {Pass} {Pass} } } FallBack “——-“ 1.Properties的基本结构,我将在下面的代码中介绍属性: _Name(“DisplayName”,Type) = defaultValue 2.一个Shader中一般都会有好几个SubShader{},他们的效果也不同,之所以有这么多是为了满足不同的显卡能力。 当我们的显卡运行到此Shader的时候,会从第一个SubShader开始检测,检测自己是否带的动这种效果,如果带不动,那么检测下一个,直到有一个能带的动的效果。 那万一我们的显卡带不动所有的SubShade,怎么办呢,看3 3.代码中最后一句话是:FallBack “Diffuse” 这句话的意思是,如果前面所有的shader代码都无法运行或者运行失败,那么会启动这个名叫Diffuse的shader 4.Subshader中有多个Pass,一个Subshader中的所有Pass会被依次执行 5.我把firstShader中多余的代码给删除了,介绍一下属性,代码如下:
Shader “Custom/firstShader”
{
Properties
{
_Int(“MyInt”,Int) = 2 //整数 Int
_Float(“MyFloat”,Float) = 1.0 //浮点数 Float
_Range(“MyRange”,Range(0.0,1.0)) = 0.5 //范围浮点数 Range
_Color(“MyColor”,Color) = (1,1,1,1) //颜色 Color
_Vector(“MyVector”,Vector) = (1,2,3,1) //四元素向量 Vector
_MainTex(“Texture”, 2D) = “white” {} //普通贴图 2D
_Cube(“MyCubeMap”,Cube) = “white”{} //正方体贴图 Cube
_3D(“My3D”,3D) = “white”{} //3D贴图 3D
}
}
6.点击保存,回到unity,新建一个材质球,并把材质球给一个cube: [