- Home /
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;
}
You should be using a Vector3 array, not Array. It will work with Array, but relatively slowly.
Answer by Mortennobel · Aug 16, 2011 at 11:57 AM
Take a look at my blog about procedural generated mesh in Unity.
http://blog.nobel-joergensen.com/2010/12/25/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 ];
7,5,6 isn't working for me. Your blog is interesting, but do you really need more verts? I thought in 3D modelling they are always shared?
I have updated the answer - there were quite a few winding order issues. You are right that in 3D modelling vertices are usually shared, but in 3D rendering they are not (since that is usually the most efficient). There is one normal for each vertex (this is computed in recalculate normals - or can be set manually. But your cube actually needs three normals for each corner. The solution is to have three vertices in each corner.
Your answer

Follow this Question
Related Questions
Autoscale Shader with multiple random texture selection. 0 Answers
Triangulate a polygon 1 Answer
Frame Rate drops when creating mesh in mobile Voxel World? 0 Answers
Dynamic Vertex Welding 1 Answer
Closest collision point 1 Answer