- Home /
Shader vs Sprites - Sorting layer (ZWrite Off not working)
Hello!
My project is a 2d game. I'm using unity 5.2 64bits, free, on windows 10.
I'm trying to use sorting layer for a material so that the mesh that uses it shows on top of a sprite.
From my research, i've found that i need a custom shader with ZWrite Off. Also, the mesh is created dynamically, and in it (MeshRenderer) i set the sorting layer. Furthermore, i changed the editor so that i coud actually check if the sorting layer is being set on the MeshRenderer (it is). Even with all that, it just does not work (mesh is always below everything). See both codes below:
Mesh Creation:
MeshRenderer mr = gameObject.AddComponent<MeshRenderer>();
mr.sortingLayerName = "Particles";
mr.materials = myMaterial;
MeshFilter mf = gameObject.AddComponent<MeshFilter>();
Mesh mesh = new Mesh();
mf.mesh = mesh;
//Vertices
// DO STUFF
//Assign Arrays
mesh.vertices = vertices;
mesh.triangles = tri;
mesh.normals = normals;
mesh.uv = uv;
Shader:
Shader "Custom/shader1" {
Properties{
_Color("Color", Color) = (1.0,1.0,1.0,1.0)
}
SubShader {
Pass {
ZWrite Off
CGPROGRAM
//pragmas
#pragma vertex vert
#pragma fragment frag
//user variables
//vertex f
uniform float4 _Color;
//base input structs
struct vertexInput {
float4 vertex : POSITION;
};
struct vertexOutput {
float4 pos : SV_POSITION;
};
vertexOutput vert(vertexInput v) {
vertexOutput o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
return o;
}
float4 frag(vertexOutput i) : COLOR {
return _Color;
}
ENDCG
}
}
}
Editor check:
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
MeshRenderer renderer = target as MeshRenderer;
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
string name = EditorGUILayout.TextField("Sorting Layer Name", renderer.sortingLayerName);
if (EditorGUI.EndChangeCheck())
{
renderer.sortingLayerName = name;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
int order = EditorGUILayout.IntField("Sorting Order", renderer.sortingOrder);
if (EditorGUI.EndChangeCheck())
{
renderer.sortingOrder = order;
}
EditorGUILayout.EndHorizontal();
}
Thanks!
Sources:
Answer by GiyomuGames · Nov 10, 2015 at 01:03 AM
Hi Artych,
I have the same problem, tried the same things and like you I didn't get good results: http://answers.unity3d.com/questions/1064940/unity-5-meshrenderer-and-sortinglayer-not-working.html
You can see my work around in my post, but maybe we are both not doing the right thing?