我们在上篇文章中提到,在Unity中实现后处理效果,需要同时结合 脚本 和 Shader,我们在这篇文章中编写所需要使用的C#脚本 和 Shader。


该语句需要在OnRenderImage生命周期函数内使用。
而该生命周期只对我们的摄像机生效
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//后处理脚本
public class P2_7_3 : MonoBehaviour
{
public Material Mat;
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
Graphics.Blit(source,destination,Mat);
}
}
把该脚本挂载在摄像机上

开启游戏后,我们看见我们的后处理Shader生效了

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;
}
Material _newMaterial = new Material(PostProcessingShader);
_newMaterial.hideFlags = HideFlags.HideAndDontSave;
return _newMaterial;
}
}


因为,后处理效果处理的是摄像机前的一个面片效果。
所以,是不需要面片剔除 和 深度效果的。需要把这两个功能相关的东西关闭,防止影响处理后的效果
Cull Off
ZWrite Off
ZTest Always
因为后处理效果几乎都是在片元着色器中实现。所以,其余部分的功能几乎都没有变化。Unity对此进行了一些优化,我们可以直接使用。



Shader "Hidden/P2_7_4"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
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;
fixed4 frag (v2f_img i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
// just invert the colors
col.rgb = 1 - col.rgb;
return col;
}
ENDCG
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//后处理脚本
public class P2_7_3 : MonoBehaviour
{
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;
}
Material _newMaterial = new Material(PostProcessingShader);
_newMaterial.hideFlags = HideFlags.HideAndDontSave;
return _newMaterial;
}
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
Graphics.Blit(source,destination,Mat);
}
}
更多【c#-Unity中后处理 脚本 和 Shader】相关视频教程:www.yxfzedu.com