Even though I looked in many places in the forum on this known issue, I was not able to fix it. I am posting my code here to check if somebody can find what is wrong.
I am generating a mesh for a cylinder from scratch in the code directly, but the standard shader still displays flat faces for the mesh.
public int nbase = 15;
public int nspan = 10;
private Mesh mesh;
void Start () {
MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
mesh = new Mesh();
mesh.name = "cylinder";
meshFilter.sharedMesh = mesh;
mesh.Clear();
mesh.vertices = getVertices();
mesh.triangles = getTriangles();
mesh.RecalculateNormals();
mesh.RecalculateBounds();
mesh.Optimize();
}
Vector3[] getVertices() {
Vector3[] vertices = new Vector3[(int)(nspan * nbase)];
int index = 0;
for (int j = 0; j < nspan; j++)
{
for (int i = 0; i < nbase; i++)
{
float a = (float)i * 2f * Mathf.PI / nbase;
vertices[index] = 0.5f * (new Vector3(Mathf.Cos(a), (float)j, Mathf.Sin(a)));
index++;
}
}
return vertices;
}
int[] getTriangles() {
int[] myTriangles = new int[(int)(3f * 2f * ((float)nspan - 1f) * ((float)nbase - 1f))];
int index = 0;
for (int j = 0; j < nspan - 1; j++)
{
for (int i = 0; i < nbase - 1; i++)
{
myTriangles[index] = i + (int)((float)j * (float)nbase);
myTriangles[index + 1] = i + (int)((float)(j + 1) * (float)nbase);
myTriangles[index + 2] = i + 1 + (int)((float)j * (float)nbase);
myTriangles[index + 3] = i + 1 + (int)((float)j * (float)nbase);
myTriangles[index + 4] = i + (int)((float)(j + 1) * (float)nbase);
myTriangles[index + 5] = i + 1 + (int)((float)(j + 1) * (float)nbase);
index += 6;
}
}
return myTriangles;
}
Here is a picture of the result. I used the MeshDisplay script to represent my normals in the editor.
I tried also to use the NormalSolver from http://schemingdeveloper.com to use alternative method to compute my normals, but it did not change the result.
What I am looking for here is to get my cylinder smooth.
Any idea/suggestion would be very welcomed.