Search Unity

Showcase Shared Vertices Script - Code Review

Discussion in 'Scripting' started by FaffyWaffles, May 17, 2022.

  1. FaffyWaffles

    FaffyWaffles

    Joined:
    Apr 10, 2020
    Posts:
    45
    So, I've written this bit of code that goes through all the vertices of a mesh, and finds all vertices that are the same. It works, and is decently fast, but I'm quite uncomfortable with all the nested for loops. Is there some potential optimization?


    Code (CSharp):
    1. public class SharedVertices : MonoBehaviour
    2. {
    3.     [Range(.0001f, .001f)] public float buffer = .0001f; //epsilon
    4.  
    5.     public class Vert
    6.     {
    7.         public List<int> sharedIndices;
    8.         public Vector3 vertex;
    9.  
    10.         public Vert(List<int> sharedIndices, Vector3 vertex)
    11.         {
    12.             this.sharedIndices = sharedIndices;
    13.             this.vertex = vertex;
    14.         }
    15.     }
    16.  
    17.     public List<Vert> sharedVerts = new List<Vert>();
    18.     public Dictionary<int, int> vertDict = new Dictionary<int, int>();
    19.  
    20.     public void FindSharedVertices(Mesh mesh)
    21.     {
    22.         Vector3[] vertices = mesh.vertices;
    23.  
    24.         sharedVerts = new List<Vert>();
    25.         vertDict = new Dictionary<int, int>();
    26.  
    27.         HashSet<int> hashedIndices = new HashSet<int>();
    28.         for (int i = 0; i < vertices.Length; i++)
    29.         {
    30.             Vert v = new Vert(new List<int>(), vertices[i]);
    31.             if (!hashedIndices.Contains(i))
    32.             {
    33.                 for (int j = 0; j < vertices.Length; j++)
    34.                 {
    35.                     if (!hashedIndices.Contains(j))
    36.                     {
    37.                         if ((vertices[i] - vertices[j]).sqrMagnitude <= (buffer * buffer))
    38.                         {
    39.                             hashedIndices.Add(j);
    40.                             v.sharedIndices.Add(j);
    41.                         }
    42.                     }
    43.                 }
    44.                 hashedIndices.Add(i);
    45.                 sharedVerts.Add(v);
    46.             }
    47.         }
    48.  
    49.         int sharedVertCount = sharedVerts.Count;
    50.         for (int i = 0; i < sharedVertCount; i++)
    51.         {
    52.             foreach (int vertIndex in sharedVerts[i].sharedIndices)
    53.                 vertDict.Add(vertIndex, i);
    54.         }
    55.     }
    56. }