Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Created September 20, 2023 04:47
Show Gist options
  • Select an option

  • Save unitycoder/fe6491a259e38625bc70dba3896a98d1 to your computer and use it in GitHub Desktop.

Select an option

Save unitycoder/fe6491a259e38625bc70dba3896a98d1 to your computer and use it in GitHub Desktop.
copy depth texture with blit
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Camera))]
public class DepthRenderTextureTest : MonoBehaviour
{
public bool OnlyRenderToDepth;
public RenderTexture RTColor;
public RenderTexture RTDepth;
public RenderTexture RTDepthCopy;
void Update()
{
Camera cam = GetComponent<Camera>();
if (RTDepthCopy)
RenderTexture.ReleaseTemporary(RTDepthCopy);
RTColor = RenderTexture.GetTemporary(1024, 1024, 0, RenderTextureFormat.Default); // no depth buffer
RTDepth = RenderTexture.GetTemporary(1024, 1024, 24, RenderTextureFormat.Depth); // only a depth buffer
RTDepthCopy = RenderTexture.GetTemporary(1024, 1024, 0, RenderTextureFormat.RFloat); // depth buffer copy
// note: if the objects being rendered have code in their fragment shader, that's still all running even
// there is no color buffer to render to. so preferably it should be using replacement shaders or only see objects // with depth only materials applied.
if (OnlyRenderToDepth)
cam.targetTexture = RTDepth;
else
cam.SetTargetBuffers(RTColor.colorBuffer, RTDepth.depthBuffer);
cam.Render();
cam.targetTexture = null;
// at this point you can sample the depth render texture
// can't use CopyTexture unless both RTs are Format.Depth, but that is an alternative!
Graphics.Blit(RTDepth, RTDepthCopy);
RenderTexture.ReleaseTemporary(RTColor);
RenderTexture.ReleaseTemporary(RTDepth);
}
void OnRenderImage(RenderTexture src, RenderTexture dst)
{
// proof that the copy worked
Graphics.Blit(RTDepthCopy, dst);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment