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类型

  1. Opaque: most of the shaders (Normal, Self Illuminated, Reflective, terrain shaders).
  2. Transparent: most semitransparent shaders (Transparent, Particle, Font, terrain additive pass shaders).
  3. TransparentCutout: masked transparency shaders (Transparent Cutout, two pass vegetation shaders).
  4. Background: Skybox shaders.
  5. Overlay: GUITexture, Halo, Flare shaders.
  6. TreeOpaque: terrain engine tree bark.
  7. TreeTransparentCutout: terrain engine tree leaves.
  8. TreeBillboard: terrain engine billboarded trees.
  9. Grass: terrain engine grass.
  10. GrassBillboard: terrain engine billboarded grass.

测试

  1. 随便写个两个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
		}
	}
}
  1. 另一个shader与之相似,修改名字为"RedShader", 同时修改RenderType为"transparent":
Shader "Unlit/RedShader"
{
	Properties
	{
		_Color("Color",Color) = (0,0,0,1)
	}
	SubShader
	{
		Tags { "RenderType"="transparent" }
		pass
		{}	
	}
}
  1. 建议一个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;
			}
			...
		}	
	}
}
  1. 写一个相机上的脚本,在启动时替换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");
	}
}

执行前
mark
执行后
mark

如果在SetReplacementShader函数中tag为空,则输出为全黄色。

结论

  1. 不知道啥时候可以用到

引用

  1. unity 替换渲染 ( Rendering with Replaced Shaders )
  2. 官方文档
  3. 浅析Unity shader中RenderType的作用及_CameraDepthNormalsTexture
posted @ 2017-03-29 01:11  RubbyZhang  阅读(5294)  评论(0编辑  收藏  举报