I have seen tutorials and questions on Unity answers and nobel-joergensen’s blog. What I really don’t understand is the clockwise winding order and the vertice assignment. If someone can share with me a proper script to make a procedural box in unity with an explanation I would be extremely grateful.

EDIT: Here is the link to the script of nobel-joergensen that i found for a cube: Click Here

What I don’t understand is what is inside the for loop. What is the triangleOffset variable doing and what is happening exactly inside the triangles.add() lines?

The loop is a way to generate each face without writing it all by hand. Each pass through the loop generates a new face of the cube. triangleOffset =i4 because the triangles have to match up to the vertices that were defined above, and, since each side has 4 vertices, you get i4.

Meshes can be confusing at first, however I think the best way to learn is using pen paper and draw out a simple primitive like a cube, then label the vertices, the split the quad faces of the cube into two triangles (spit along diagonals). Then go through face by face and write out the vertex orders.

Clockwise winding order is used for a ‘consistent’ order of the indices to vertices that form a triangle. The actual order of the vertices referenced in a triangle define whether it is forward or back facing. So if you draw a triangle on a piece of paper and label the vertices A,B,C in clockwise order then the ‘face’ of the triangle would be facing you out of the paper. If you defined the triangle using C,B,A order then the face of the triangle would be facing out of the back of the piece of paper away from you.

Another aspect that can be confusing at first is sharing of vertex data, a simple cube might only need 8 vertices to define it, but this would mean each face shares the vertex normal with other faces. This would create a ‘smooth’ (ish) shaded cube, where as what you’d probably want is a ‘faceted’ look, where each face has a constant shading across it. In order to achieve this, each vertex per side needs to be unique, so that you can provide unique normals. Since a vertex is shared by 3 cube sides, that would mean you need a total of 8*3 vertices (24) and 24 normals. The same is true if vertices do not share uv’s or tangents or vertex colors.

Looking at the code link you provided, this is why he has 24 vertices (vectors) define, 4 for each face. The loop and offset variable is simply an efficient code method for defining the triangle faces by indexing the correct vertices. What might help here is to add some debug statements into that code, which simply dump out each triangles face vertex indices (i.e. 3 indices into the vertex array per triangle). Then use the information provided in his code to draw out a cube on paper and mark up all the vertex indices and the triangles to see how everything is fitted together.