# How can I make this code more efficient?

This loops through each vertex in pieceMesh, finds the closest vertex to it in tempPieceMesh and copies its boneweights. I’m using nested for loops to go through each vertex so it takes a second or two to run through. I was hoping to be able to cut that time down as it will have to do this for a few more meshes.

``````Mesh pieceMesh = piece.GetComponent<SkinnedMeshRenderer>().sharedMesh;
Mesh tempPieceMesh = tempPiece.GetComponent<SkinnedMeshRenderer>().sharedMesh;
BoneWeight[] weights = tempPieceMesh.boneWeights;

// Iterate through piece's vertices, find closest vertice in tempPieceMesh and copy its boneweights
for(int i = 0; i < pieceMesh.vertexCount; i++)
{
// Check vertex distance. If there is a higher one, set verDistance to it
float checkVertDis = 0.0f;
float vertDistance = 10.0f;

for(int j = 0; j < tempPieceMesh.vertexCount; j++)
{
checkVertDis = Vector3.Distance(pieceMesh.vertices*, tempPieceMesh.vertices[j]);*
``````

// If we find a lower distance, set vertdistance to it and copy the boneweights
if(checkVertDis < vertDistance)
{
vertDistance = checkVertDis;

weights = tempPieceMesh.boneWeights[j];
}
}
}
pieceMesh.boneWeights = weights;
Edit: Here’s the fixed code using @CHPedersen’s advice:
Mesh pieceMesh = piece.GetComponent().sharedMesh;
Mesh tempPieceMesh = tempPiece.GetComponent().sharedMesh;
BoneWeight[] weights = tempPieceMesh.boneWeights;
BoneWeight[] newWeights = pieceMesh.boneWeights;
// Copy the positions of pieceMesh and tempPieceMesh vertices into new array to use in distance function
Vector3[] pVertices = pieceMesh.vertices;
Vector3[] tPVertices = tempPieceMesh.vertices;
// Iterate through piece’s vertices, find closest vertice in tempPieceMesh and copy its boneweights
for(int i = 0; i < pieceMesh.vertexCount; i++)
{
// Check vertex distance. If there is a higher one, set verDistance to it
float checkVertDis = 0.0f;
float vertDistance = 10.0f;
for(int j = 0; j < tempPieceMesh.vertexCount; j++)
{
checkVertDis = Vector3.Distance(pVertices*, tPVertices[j]);*
// If we find a lower distance, set vertdistance to it
if(checkVertDis < vertDistance)
{
vertDistance = checkVertDis;
newWeights = weights[j];
}
}
}
pieceMesh.boneWeights = newWeights;

By far the worst performance drawback of that code snippet is that you’re accessing Mesh.vertices inside the for-loop. That property looks innocent, but Unity is in fact instantiating and returning a deep copy every time you access it, which adds an incredibly unnecessary overhead on each access of pieceMesh.vertices and tempPieceMesh.vertices[j], especially if that mesh has a lot of vertices.
Copy out the vertex arrays ONCE outside the for loop, then index into that copy to do your distance calculations.