45 lines
1.6 KiB
C#
45 lines
1.6 KiB
C#
using UnityEngine;
|
||
using UnityEngine.Rendering;
|
||
using UnityEngine.Rendering.Universal;
|
||
|
||
public class PixelatePass : ScriptableRenderPass
|
||
{
|
||
private Material m_PixelateMaterial;
|
||
|
||
// 构造函数,接收材质
|
||
public PixelatePass(Material pixelateMaterial)
|
||
{
|
||
this.m_PixelateMaterial = pixelateMaterial;
|
||
}
|
||
|
||
// 这个方法在每一帧渲染该Pass之前被调用
|
||
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
|
||
{
|
||
// 1. 安全检查
|
||
if (m_PixelateMaterial == null)
|
||
{
|
||
Debug.LogError("Pixelate Material not assigned to the pass.");
|
||
return;
|
||
}
|
||
// 如果渲染的不是游戏主相机(例如Scene视图的相机),则直接返回,避免在编辑器里也显示效果
|
||
if (renderingData.cameraData.cameraType != CameraType.Game)
|
||
{
|
||
return;
|
||
}
|
||
|
||
// 2. 获取命令缓冲区
|
||
CommandBuffer cmd = CommandBufferPool.Get("PixelatePass");
|
||
|
||
// 3. 【核心修正】在Execute方法内部,安全地获取当前摄像机的渲染目标
|
||
// URP 12+ 使用 renderingData.cameraData.renderer.cameraColorTargetHandle
|
||
RTHandle source = renderingData.cameraData.renderer.cameraColorTargetHandle;
|
||
|
||
// 4. 执行Blit操作
|
||
// 将源纹理(source)通过我们的材质处理后,再写回源纹理(source)
|
||
Blit(cmd, source, source, m_PixelateMaterial, 0);
|
||
|
||
// 5. 执行并释放命令缓冲区
|
||
context.ExecuteCommandBuffer(cmd);
|
||
CommandBufferPool.Release(cmd);
|
||
}
|
||
} |