Hi, there
I developing 2D game
I want render 3d models in Unity
I writted some script for render and save png file with alpha channel
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;
public class PhotoTool : MonoBehaviour
{
private string path;
public bool shot = false;
public Camera cam;
public string color;
public Transform unit;
void Start()
{
if (path == null)
{
SelectDir ();
}
int angle = 0;
for (int i = 0; i < 8; i++)
{
Shot ();
angle += 45;
unit.localEulerAngles = Vector3.up * angle;
}
}
public void Shot()
{
int sqr = 512;
RenderTexture tempRT = new RenderTexture(sqr,sqr, 0 );
cam.targetTexture = tempRT;
cam.Render();
RenderTexture.active = tempRT;
Texture2D virtualPhoto = new Texture2D(sqr,sqr, TextureFormat.ARGB32, false);
virtualPhoto.ReadPixels( new Rect(0, 0, sqr,sqr), 0, 0);
RenderTexture.active = null;
cam.targetTexture = null;
byte[] bytes = virtualPhoto.EncodeToPNG();
File.WriteAllBytes(path + "/"+ unit.name + "_" + color + "_" + unit.transform.localEulerAngles.y + ".png", bytes);
}
public void SelectDir()
{
path = EditorUtility.OpenFolderPanel ("","","");
}
}
So this scripts works, but i get uncorrect render
Look:
There is expected result (used simple screenshot)

But i got this
So, how to fix this?
I checked this on 5.2.2 | 5.3.4 | 5.4.0b but same result
Thanks, Unity Community
This is because you have disabled the “depth buffer”. Depth buffer is what your GPU need to know which pixels are in front of the others.
You need to replace this:
RenderTexture tempRT = new RenderTexture(sqr,sqr, 0 );
… with this:
RenderTexture tempRT = new RenderTexture(sqr,sqr, 24 );
This tells the GPU that your render texture has 24-bit depth buffer.