Created
September 20, 2023 04:47
-
-
Save unitycoder/fe6491a259e38625bc70dba3896a98d1 to your computer and use it in GitHub Desktop.
Revisions
-
unitycoder created this gist
Sep 20, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,46 @@ 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); } }