Procedural cube generation

I’m trying to make a cube appear by prcedurally creating the mesh. I have got all the triangles in the right place, except for the last one! I’m trying to create a simple 1x1x1 cube - I’ve attempted all possible combinations for the last triangle - and none of them work. All produce a triangle the wrong way round.
Anyway, here is the code:

var newVertices : Vector3[];
var newUV : Vector2[];
var newTriangles : int[];
var material : Texture2D;

function Start () {
var mesh : Mesh = new Mesh ();
GetComponent(MeshFilter).mesh = mesh;
mesh.Clear();
//Actual creation.
var p1 = Vector3(0,0,0);
var p2 = Vector3(1,0,0);
var p3 = Vector3(0,1,0);
var p4 = Vector3(0,0,1);
var p5 = Vector3(1,0,1);
var p6 = Vector3(1,1,0);
var p7 = Vector3(0,1,1);
var p8 = Vector3(1,1,1);

newVertices = new Array (p1,p2,p3,p4,p5,p6,p7,p8);

newTriangles = [
0,1,2,
1,2,5,

3,0,1,
1,4,3,

0,3,2,
2,3,6,

1,4,5,
5,7,4,

6,3,4,
6,4,7,

6,5,2,
//problem line below
7,6,5
];

mesh.vertices = newVertices;
mesh.triangles = newTriangles;
mesh.uv = newUV;
//I could UV map it, but I can't be bothered right now. Maybe later?
mesh.RecalculateNormals();  
mesh.RecalculateBounds();  
mesh.Optimize(); 
renderer.material.color = Color.gray;
}

Take a look at my blog about procedural generated mesh in Unity.

You are doing a few things wrong:

  • Most likely you need more vertices (since each normal are shared between all vertices in each triangle). If you don’t do this, your cube will be shaded very odd.

  • Be careful about the winding order. The correct order of your vertices are:

    newTriangles = [
    0,2,1,
    1,2,5,

    3,0,1,
    1,4,3,

    0,3,2,
    2,3,6,

    1,5,4,
    5,7,4,

    6,3,4,
    6,4,7,

    6,5,2,
    7,5,6
    ];