在 Unity Shader 中,变量除了在代码段(CGPROGRAM)中声明外,还必须在 Properties 块中同步声明,才能正确使用,并且能在 Inspector 视图中显示。

Properties 中的声明格式为:

变量名字(Inspector中显示的名字, 类型)= 默认值

Properties 类型与 CG 语言类型对照

Properties 类型示例默认值对应 CG 语言类型
Range(min,max)0float, half, fixed
Float0.0float, half, fixed
Int1int
Color(1,1,1,1) 或 (1,1,1)float4, float3, half4, fixed4
vector(1,1,1,1) 或 (1,1,1)float4, float3, half4, fixed4
2D"white" {}sampler2D
3D"white" {}sampler3D
Cube"white" {}samplerCUBE

数据类型说明

CG 语言中常用的三种浮点精度类型:

  • float:32 位浮点数
  • half:16 位浮点数
  • fixed:12 位定点数

各类型的精度规格如下:

  • float:s23e8("fp32")IEEE single precision floating point
  • half:s10e5("fp16")floating point w/ IEEE semantics
  • fixed:S1.10 fixed point, clamping to [-2, 2)
  • double:s52e11("fp64")IEEE double precision floating point

常量后缀

  • d for double
  • f for float
  • h for half
  • i for int
  • l for long
  • s for short
  • t for char
  • u for unsigned,也可后接 stil
  • x for fixed

示例代码

Shader "Custom/NewShader" {
	Properties {
		_MainTex ("Base (RGB)", 2D) = "white" {}
        _color("color",Color)=(1,1,1)
	}
	SubShader {
		Tags { "RenderType"="Opaque" }
		LOD 200

		CGPROGRAM
		#pragma surface surf Lambert

		sampler2D _MainTex;
		float3 _color;

		struct Input {
			float2 uv_MainTex;
		};

		void surf (Input IN, inout SurfaceOutput o) {
			half4 c = tex2D (_MainTex, IN.uv_MainTex);


          c.rgb=_color;

			o.Albedo = c.rgb;
			o.Alpha = c.a;
		}
		ENDCG
	}
	FallBack "Diffuse"
}