Unity Shader 基础(1): RenderType & ReplacementShader
很多Shader中都会定义RenderType这个类型,但是一直搞不明白到底是干嘛的,官方文档是这样结解释的:Rendering with Replaced Shaders
Rendering with Replaced Shaders
shader通过camera中 Camera.RenderWithShader 和 Camera.SetReplacementShader实现替换功能,这两个方法都接受两个参数:Shader和replacementTag ,根据情况:
- replacementTag 为空,场景中所有物体都会使用replacement shader进行渲染
- replacementTag 不为空,如果物体不存在tag则不进行渲染。
- replacementTag 不为空,如果物体shgader中存在、与之placement shader中相同的tag',则使用placement shader中对应subshader进行渲染,否则不渲染。
RenderType类型
- Opaque: most of the shaders (Normal, Self Illuminated, Reflective, terrain shaders).
- Transparent: most semitransparent shaders (Transparent, Particle, Font, terrain additive pass shaders).
- TransparentCutout: masked transparency shaders (Transparent Cutout, two pass vegetation shaders).
- Background: Skybox shaders.
- Overlay: GUITexture, Halo, Flare shaders.
- TreeOpaque: terrain engine tree bark.
- TreeTransparentCutout: terrain engine tree leaves.
- TreeBillboard: terrain engine billboarded trees.
- Grass: terrain engine grass.
- GrassBillboard: terrain engine billboarded grass.
测试
- 随便写个两个shader,建立对应的材质:
Shader "Unlit/BlueShader"
{
Properties
{
_Color("Color",Color) = (0,0,0,1)
}
SubShader
{
Tags { "RenderType"="transparent" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata {float4 vertex : POSITION;};
struct v2f{
float4 vertex : SV_POSITION;
};
fixed4 _Color ;
v2f vert (appdata v){
v2f o;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);return o;
}
fixed4 frag (v2f i) : SV_Target{
fixed4 col = _Color;return col;
}
ENDCG
}
}
}
- 另一个shader与之相似,修改名字为"RedShader", 同时修改RenderType为"transparent":
Shader "Unlit/RedShader"
{
Properties
{
_Color("Color",Color) = (0,0,0,1)
}
SubShader
{
Tags { "RenderType"="transparent" }
pass
{}
}
}
- 建议一个Replacement shader,和rendshader相似,并将输出颜色修改为固定黄色。之修改下名字:
Shader "Unlit/ReplacementShader"
{
Properties
{
_Color("Color",Color) = (0,0,0,1)
}
SubShader
{
Tags { "RenderType"="transparent" }
pass
{
...
//输出为黄色,如果替换了输出为黄色
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = fixed4(1,1,0,0);
return col;
}
...
}
}
}
- 写一个相机上的脚本,在启动时替换shader
public class ReplaceMent : MonoBehaviour {
public Shader rpShader;
// Use this for initialization
void Start ()
{
//全部替换渲染
//GetComponent<Camera> ().SetReplacementShader(rpShader,"");
//RenderType="rpShader中RenderType"的sunshader进行渲染,
GetComponent<Camera> ().SetReplacementShader(rpShader,"RenderType");
}
}
执行前
执行后
如果在SetReplacementShader函数中tag为空,则输出为全黄色。
结论
- 不知道啥时候可以用到