文章目錄
- 前言
- 一、我們先來PS看一下黑白閥值的效果
- 二、使用step(a,b)函數實現效果
- 三、實現腳本控制黑白閥值
- 1、在Shader屬性面板定義控制閥值變量
- 2、把step的a改為_Value
- 3、在后處理腳本設置公共成員變量,并且設置范圍為(0,1)
- 4、在Graphics.Blit賦值材質前,給材質的_Value賦值
- 四、最終代碼 和 效果
- Shader:
- C#:
前言
在上篇文章中,我們講解了Unity后處理的腳本和Shader。我們在這篇文章中實現一個黑白的后處理Shader
- Unity中后處理 腳本 和 Shader
一、我們先來PS看一下黑白閥值的效果
二、使用step(a,b)函數實現效果
由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);
}
三、實現腳本控制黑白閥值
1、在Shader屬性面板定義控制閥值變量
_Value(“Value”,float) = 0.2
2、把step的a改為_Value
fixed4 frag (v2f_img i) : SV_Target
{fixed4 col = tex2D(_MainTex, i.uv);return step(_Value,col.r);
}
3、在后處理腳本設置公共成員變量,并且設置范圍為(0,1)
[Range(0,1)]public float Value = 0;
4、在Graphics.Blit賦值材質前,給材質的_Value賦值
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{Mat.SetFloat("_Value",Value);Graphics.Blit(source,destination,Mat);
}
四、最終代碼 和 效果
Shader:
Shader "Hidden/P2_7_4"
{Properties{_MainTex ("Texture", 2D) = "white" {}_Value("Value",float) = 0}SubShader{// No culling or depthCull Off ZWrite Off ZTest AlwaysPass{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);}
}