unity post processing stack v2——正式入坑第二弹

本篇主要讲解如何实现自定义的一个后处理效果,参考网址:
https://docs.unity3d.com/Packages/[email protected]/manual/Writing-Custom-Effects.html

第1步:
编写一个C#脚本:
名字必须是:Grayscale.cs

using System;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;

[Serializable]
[PostProcess(typeof(GrayscaleRenderer), PostProcessEvent.AfterStack, "Custom/Grayscale")]
public sealed class Grayscale : PostProcessEffectSettings
{
     
    [Range(0f, 1f), Tooltip("Grayscale effect intensity.")]
    public FloatParameter blend = new FloatParameter {
      value = 0.5f };

    public override bool IsEnabledAndSupported(PostProcessRenderContext context)
    {
     
        return enabled.value
            && blend.value > 0f;
    }
}

public sealed class GrayscaleRenderer : PostProcessEffectRenderer<Grayscale>
{
     
    public override void Render(PostProcessRenderContext context)
    {
     
        var sheet = context.propertySheets.Get(Shader.Find("Hidden/Custom/Grayscale"));
        sheet.properties.SetFloat("_Blend", settings.blend);
        context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0);
    }
}

第2步:编写一个shader文件Grayscale.shader

Shader "Hidden/Custom/Grayscale"
{
     
	HLSLINCLUDE
	#include "../../Shaders/StdLib.hlsl"
	TEXTURE2D_SAMPLER2D(_MainTex, sampler_MainTex);

	float _Blend;
	float4 Frag(VaryingsDefault i) : SV_Target
	{
     
		float4 color = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.texcoord);
		float luminance = dot(color.rgb, float3(0.2126729, 0.7151522, 0.0721750));
		color.rgb = lerp(color.rgb, luminance.xxx, _Blend.xxx);
		return color;
	}

	ENDHLSL

	SubShader
	{
     
		Cull Off ZWrite Off ZTest Always
		Pass
		{
     
			HLSLPROGRAM

				#pragma vertex VertDefault
				#pragma fragment Frag

			ENDHLSL
		}
	}
}

第3步:写一个编辑器文件:GrayscaleEditor.cs

using UnityEditor.Rendering.PostProcessing;

[PostProcessEditor(typeof(Grayscale))]
public sealed class GrayscaleEditor : PostProcessEffectEditor<Grayscale>
{
     
    SerializedParameterOverride m_Blend;

    public override void OnEnable()
    {
     
        m_Blend = FindParameterOverride(x => x.blend);
    }

    public override void OnInspectorGUI()
    {
     
        PropertyField(m_Blend);
    }
}

开启grayscale的效果:

unity post processing stack v2——正式入坑第二弹_第1张图片
未开启grayscale的效果:
unity post processing stack v2——正式入坑第二弹_第2张图片

你可能感兴趣的:(Unity)