Question by
squarefanatic · Sep 28, 2015 at 05:58 AM ·
cameratexture2drendertexturereadpixels
Rendering Camera to PNG produces completely grey image.
The following Behaviour is attached to a new GameObject programatically, and when it's done it doesn't output a rendered image from the Camera, rather a completely grey image. What have a I done wrong or overlooked?
using UnityEngine;
namespace Cartographer
{
class MapCameraBehaviour : MonoBehaviour
{
private int size = 1000;
private Camera camera;
private RenderTexture renderTexture;
private Texture2D texture;
private bool render = false;
private int renderFrameDelay = 0;
private bool renderNow = false;
void Log(string message)
{
//some logging code
}
void Awake()
{
Log("Awake()");
camera = GetComponent<Camera>();
if (camera == null)
{
camera = gameObject.AddComponent<Camera>();
camera.nearClipPlane = 0.1f;
camera.farClipPlane = 2000f;
camera.renderingPath = RenderingPath.Forward;
camera.depth = 100;
camera.transform.position = new Vector3(0.0f, 100.0f, 0.0f);
}
else
{
Log("Existing camera.");
}
if (camera != null)
{
Log("Camera found.");
renderTexture = new RenderTexture(size, size, 0);
texture = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false);
camera.targetTexture = renderTexture;
RenderTexture.active = renderTexture;
render = true;
renderFrameDelay = 100;
renderNow = false;
}
else
{
Log("Camera not found.");
}
}
void Update()
{
if (render)
{
if (renderFrameDelay <= 0)
{
render = false;
renderNow = true;
QualitySettings.antiAliasing = 0;
camera.Render();
}
else
{
renderFrameDelay--;
}
}
}
void OnPostRender()
{
if (renderNow == true)
{
renderNow = false;
Log("OnPostRender()");
texture.ReadPixels(new Rect(0.0f, 0.0f, renderTexture.width, renderTexture.height), 0, 0);
byte[] bytes = texture.EncodeToPNG();
System.IO.File.WriteAllBytes(Application.dataPath + "/texture.png", bytes);
camera.targetTexture = null;
RenderTexture.active = null;
DestroyImmediate(texture);
DestroyImmediate(renderTexture);
Log("Done.");
}
}
}
}
Comment
Were you able to solve your problem I am running into the same issue
Answer by saschandroid · Sep 29, 2015 at 07:10 AM
Have you tried to apply the texture after reading the pixels?
texture.ReadPixels(new Rect(0.0f, 0.0f, renderTexture.width, renderTexture.height), 0, 0);
texture.Apply();
Also make sure the texture is Read/Write enabled.
I have yeah, it made no difference.
Sorry for the late reply. The Unity emails have been going to SPA$$anonymous$$. >_<
I have been facing the same problem... Did you find a solution?