Hi guys,
I am trying to retrieve and save on a Texture 2D pixel color data from depth texture mode. Here’s my code which is a merge of different contribution on the web:
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
[ExecuteInEditMode]
public class CameraScript : MonoBehaviour
{
#region ' Fields '
public Material mat;
private Texture2D mTexture;
public Renderer screenGrabRenderer;
#endregion
#region ' Methods '
void Start()
{
mCamera = GameObject.FindObjectOfType<Camera>();
GetComponent<Camera>().depthTextureMode = DepthTextureMode.Depth;
mTexture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
}
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
Graphics.Blit(source, destination, mat);
RenderTexture.active = destination;
mTexture = new Texture2D(source.width, source.height);
mTexture.ReadPixels(new Rect(0, 0, destination.width, destination.height), 0, 0);
mTexture.Apply();
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(destination);
}
#endregion
}
Actually, I would like to have a Color array with value on a gray scale: destionation variable in the OnRenderImage should have this information and I should simply transform it in a Texture2D, but on reading pixel Unity reports a null reference exception. Am I on the right way? What am I missing?