# Material looks different on programatically generated mesh compared to resized default cube mesh

I've written some code that generates a mesh from some 2D nodes, generating both triangles and vertices. It seems to have worked pretty well, since I get a solid mesh without any weird rendering artefacts:

As you can already see in the preview, I am experiencing some problems with lighting and materials, despite the triangles and vertices being completely valid and wound correctly.

This is probably shown best by comparing this with a mesh created via right click > 3D Object > Cube, with the exact same material assigned as the programmatic mesh:

I have tried calling RecalculateNormals() on the mesh, but this doesn't help.

I'm really stuck trying to work out what's going on, so any help is very much appreciated.

Edit:

In lieu of the code, here are the vertices and triangles that I'm using in this mesh:

Vertices: [(0.5, 0.0, 0.5), (0.5, 0.0, -0.5), (-0.5, 0.0, -0.5), (-0.5, 0.0, 0.5), (0.5, -0.5, 0.5), (0.5, -0.5, -0.5), (-0.5, -0.5, -0.5), (-0.5, -0.5, 0.5)]

Triangles: [(3, 0, 1), (3, 1, 2), (5, 4, 7), (6, 5, 7), (0, 4, 5), (5, 1, 0), (1, 5, 6), (6, 2, 1), (2, 6, 7), (7, 3, 2), (3, 7, 4), (4, 0, 3)]


For @Phillip:

Mesh editing = Instantiate(new Mesh());

Vector3[] vertices;
int[] triangles;
GenerateVertices(out vertices);
GenerateTriangles(in vertices, out triangles);

editing.Clear();
editing.vertices = vertices;
editing.triangles = triangles;
editing.RecalculateNormals();

• Can you please show us your code so we can check for any mistakes you might have made? – Philipp Jul 2 '20 at 14:22
• I'm reluctant to post all of it, because there's a lot. Any specific part that you would find useful @Philipp? – jumbot Jul 2 '20 at 14:23
• The code which builds the Mesh object. It's just 8 vertices, so that shouldn't be that much. – Philipp Jul 2 '20 at 14:26
• It looks like you're sharing the same 8 vertices among all 12 triangles, instead of duplicating vertices for normal splits. This gives you one shared normal where three faces meet at a corner, so RecalculateNormals() will make this the average of the three face normals, giving your shading a smooth, blobby look instead of hard creased edges. – DMGregory Jul 2 '20 at 14:26
• @DMGregory thank you! That's likely what's happening. I'll try duplicating vertices at normal splits and seeing if that solves it. – jumbot Jul 2 '20 at 14:29

• @DMGregory I would have agreed until I actually tried out Philipp's suggestion, and, using Unwrapping.GenerateSecondaryUVSet I actually managed to fix it perfectly! Seems that Unity uses the secondary UV set for lightmapping, and this function literally exists just for this purpose. Thanks either way. – jumbot Jul 2 '20 at 17:01