添加并使用Properties#
Inspector屬性
Properties是shader的一個非常重要的一部分,它可以設置使用shader的material在Insppector視圖的展示信息,可以定義一些參數屬性讓我們在后面使用,以上是默認屬性的展示。
準備階段
以下的腳本中的第二行開始,可以看到一個Properties和{}包含的信息,這些就是我們需要操作的部分:
Shader "Custom/StandardDiffuse" {
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 {
CGPROGRAM
struct Input {
};
void surf (Input IN, inout SurfaceOutputStandard o) {
}
ENDCG
}
FallBack "Diffuse"
}
如何實現
- 創建一個默認的Surface Shader;
- 在Properties添加兩行代碼:
_AmbientColor("Ambient Color", Color) = (1,1,1,1)
_MySliderValue("This is a Slider", Range(0,10)) = 2.5 - 在
fixed4 _Color
腳本后添加兩行腳本
float4 _AmbientColor;
float4 _MySliderValue; - 修改
surf
函數的第一行:
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * pow((_Color+ _AmbientColor), _MySliderValue); - 用生成的shader創建一個新的material并運用到一個Cube上,可以自己去嘗試修改material的參數。
具體效果
左邊是默認的材質球效果,右邊是運用新shader后稍微調節后的效果.png
左邊是默認的材質球效果,右邊是運用新shader后稍微調節后的效果.png
解釋說明
- 整體代碼效果如下:
Shader "Custom/StandardDiffuse/Properties" {
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
_AmbientColor("Ambient Color", Color) = (1,1,1,1)
_MySliderValue("This is a Slider", Range(0,10)) = 2.5
}
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;
float4 _AmbientColor;
float4 _MySliderValue;
void surf (Input IN, inout SurfaceOutputStandard o) {
// Albedo comes from a texture tinted by color
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * pow((_Color+ _AmbientColor), _MySliderValue);
o.Albedo = c.rgb;
// Metallic and smoothness come from slider variables
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
}
ENDCG
}
FallBack "Diffuse"
}
注意查看Properties中的代碼,大家不難發現大體所有的代碼都呈現以下的樣式:
Properties代碼結構圖.png
- 第一個是Variable Name,是你的代碼中將要使用的名字;第二個是Inspector GUI Name Type,就是最初在Inspector視圖下我們看到的信息,可以稍微修改查看效果;第三個是Property的類型,Unity支持的類型如下;第四個是默認值,細心的可以發現部分比如2D,Rect,Cube還要再加個{};作為Properties的內容以上四部分缺一不可
Property類型支持.png
- 操作第3步的參數標識了
surf
中調用的參數,需得與上面Properties中定義的一致,否則不能識別。 - 操作第4步是Properties中參數的具體函數調用,細心的可以發現我們使用了pow函數,這是一個指數函數,具體有哪些函數可以使用的,可以參考鏈接http://http.developer.nvidia.com/CgTutorial/cg_tutorial_appendix_e.html 不在surf內操作的Properties屬性是不會起到作用的。
欲知后事如何,且聽下回分解