Article directory
Preface
In the previous article, we explained Unity post-processing scripts and Shaders. In this article we implement a black and white post-processing Shader
1. Let’s first look at the effect of black and white threshold in PS
2. Use the step(a,b) function to achieve the effect
由PS内效果可得出,使用step函数可以达到类型的效果
在PS内,黑白阀值是值越小越白,而step函数 a<b 才返回1(白色)
所以,我们让 控制变量 为 a ,颜色通道 为 b。实现出一样的效果
fixed4 frag (v2f_img i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
return step(0.2,col.r);
}
3. Implement script control of black and white thresholds
1. Define the control threshold variable in the Shader property panel
_Value(“Value”,float) = 0.2
2. Change a in step to _Value
fixed4 frag (v2f_img i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
return step(_Value,col.r);
}
3. Set public member variables in the post-processing script, and set the range to (0, 1)
[Range(0,1)]public float Value = 0;
4. Before assigning the material to Graphics.Blit, assign a value to the _Value of the material.
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
Mat.SetFloat("_Value",Value);
Graphics.Blit(source,destination,Mat);
}
4. Final code and effects
Shader:
Shader "Hidden/P2_7_4"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Value("Value",float) = 0
}
SubShader
{
// No culling or depth
Cull Off
ZWrite Off
ZTest Always
Pass
{
CGPROGRAM
#pragma vertex vert_img
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _MainTex;
fixed _Value;
fixed4 frag (v2f_img i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
return step(_Value,col.r);
}
ENDCG
}
}
}
C#:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//后处理脚本
[ExecuteInEditMode]
public class P2_7_3 : MonoBehaviour
{
[Range(0,1)]public float Value = 0;
public Shader PostProcessingShader;
private Material mat;
public Material Mat
{
get
{
if (PostProcessingShader == null)
{
Debug.LogError("没有赋予Shader");
return null;
}
if (!PostProcessingShader.isSupported)
{
Debug.LogError("当前Shader不支持");
return null;
}
//如果材质没有创建,则根据Shader创建材质,并给成员变量赋值存储
if (mat == null)
{
Material _newMaterial = new Material(PostProcessingShader);
_newMaterial.hideFlags = HideFlags.HideAndDontSave;
mat = _newMaterial;
return _newMaterial;
}
return mat;
}
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
Mat.SetFloat("_Value",Value);
Graphics.Blit(source,destination,Mat);
}
}