Function to calculate smooth normals in mesh

To give the illusion of an object appearing smooth, using vertex normals which are the average of each nearest face can be used for each vertex. When lighting is calculated the object then appears smooth. In graphics editors, such as Blender, you can make the object automatically have these smooth normals.
However, if you are creating a mesh in unity, the default normal calculating function only calculates face normals. I am trying to create a function that will smooth out the face after this point.

I am first trying to do this with the default sphere mesh in unity, as I have an idea of what a successful smooth would look like. Here is my current code:

public static void Smooth(Mesh mesh){

        Dictionary<Vector3, List<int>> unique = new Dictionary<Vector3, List<int>> (); //All individual vertex, with each value of it.

        for(int i=0; i<mesh.vertices.Length; i++){
            if(!unique.ContainsKey(mesh.vertices[i]))
                unique.Add(mesh.vertices[i], new List<int>());

            unique[mesh.vertices[i]].Add(i);
        }

        Dictionary<Vector3, List<Vector3>> normals = new Dictionary<Vector3, List<Vector3>> ();
        foreach (KeyValuePair<Vector3, List<int>> i in unique) {
            normals[i.Key] = new List<Vector3>();
         
            foreach(int t in i.Value){
                normals[i.Key].Add(mesh.normals[t]);
            }
        }
        Dictionary<Vector3, Vector3> averageNormals = new Dictionary<Vector3, Vector3> ();
     
        foreach(KeyValuePair<Vector3, List<Vector3>> i in normals){
            Debug.Log(i.Value.Count);
            averageNormals.Add(i.Key,Maths.Average(i.Value.ToArray()));
        }
        for(int i=0; i<mesh.vertices.Length; i++){
            mesh.normals[i] = averageNormals[mesh.vertices[i]];
        }
}

Screenshots of how the sphere looks after the code is run on it can be seen as an attachment, but I have a feeling this is an obvious problem in the code that I’m simply missing.

Did you ever get any further with this? I’m facing the same issue. Thanks!

1 Like