I’m using Unity to create a 2D game and I’m having a problem with meshes. It seems that triangles in the same mesh are drawn in creation order instead of depth order.
I created a simple example:
public class MeshTest : MonoBehaviour
{
Mesh mesh;
void Start ()
{
mesh = GetComponent<MeshFilter> ().mesh;
BuildMesh ();
}
List<Vector3> newVertices = new List<Vector3>();
List<int> newTriangles = new List<int>();
List<Color> newColor = new List<Color>();
void BuildMesh()
{
Vector3 pos = Vector3.zero;
// Create three quads in the mesh
GenerateQuad (Vector3.zero, Color.red);
GenerateQuad (new Vector3(1f, 1f, 1f), Color.yellow);
GenerateQuad (new Vector3(0.5f, 0.5f, 0.5f), Color.green);
// The green square has a z coordinate in-between the other two squares
mesh.Clear ();
mesh.vertices = newVertices.ToArray();
mesh.triangles = newTriangles.ToArray();
mesh.colors = newColor.ToArray ();
mesh.Optimize ();
mesh.RecalculateNormals ();
newVertices.Clear ();
newTriangles.Clear ();
newColor.Clear ();
}
void GenerateQuad(Vector3 topLeft, Color color)
{
int triangleIndex = newVertices.Count;
float x = topLeft.x;
float y = topLeft.y;
float z = topLeft.z;
newVertices.Add( new Vector3 (x, y, z) );
newVertices.Add( new Vector3 (x + 1f, y, z));
newVertices.Add( new Vector3 (x, y - 1f, z));
newVertices.Add( new Vector3 (x + 1f, y - 1f, z));
newTriangles.Add(triangleIndex+0);
newTriangles.Add(triangleIndex+1);
newTriangles.Add(triangleIndex+2);
newTriangles.Add(triangleIndex+1);
newTriangles.Add(triangleIndex+2);
newTriangles.Add(triangleIndex+3);
newColor.Add (color);
newColor.Add (color);
newColor.Add (color);
newColor.Add (color);
}
}
When I run a scene with just this game object in I see this:
[35900-screen+shot+2014-11-27+at+01.17.35.png|35900]
The green square is on top of the other two when it should be in between them.
Any ideas what I’m doing wrong? Is this the normal behaviour?
Thanks