I’m working on an application that uses unity as a rendering engine and sends the result to a windows forms program. My problem is that the framebuffer from which I ReadPixels() doesn’t seem to have an alpha channel. I’ve read that this is because of:
#pragma surface surf Lambert alpha
which sets ColorMask RGB. I have written a custom shader that looks like this:
This yields some weird artifacts surrounding the objects rendered with transparency. My question is: how does this shader differ from the one that ships with unity (Transparent - Diffuse)? Or how could I write a shader that does what Transparent - Diffuse does, but also get the alpha channel correctly?
I found a solution/workaround if anyone is interested. First I use a script that exports the compiled version of my surface shaders (I used the transparent ones that ship with Unity). Then I modify this line in the compiled shader: “ColorMask RGB” to “ColorMask RGBA”. Below I post the code for the editor script, the source shader, and the first few lines of the compiled shader.
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Linq;
public static class MenuItemExportShaders
{
[MenuItem("Window/Export Compiled Shaders")]
public static void ExportCompiledShaders()
{
string folderPath = Application.dataPath + "/../Assets/ExportedShaders/";
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
var allShaders = AssetDatabase.GetAllAssetPaths().Where(x => x.Contains(".shader") !x.Contains("Compiled"));
foreach (var shaderPath in allShaders)
{
var shader = (Shader)AssetDatabase.LoadAssetAtPath(shaderPath, typeof(Shader));
var compiledShaderString = (new SerializedObject(shader)).FindProperty("m_Script").stringValue;
if (compiledShaderString == null)
continue;
var outputPath = folderPath + Path.GetFileNameWithoutExtension(shaderPath) + " Compiled.shader";
using (var sw = File.CreateText(outputPath))
{
sw.Write(compiledShaderString);
sw.Flush();
sw.Close();
}
}
EditorUtility.DisplayDialog("Success...", "Exported all shader assets...", "OK");
}
}