C# unity perfomance issue

I am writing a function that returns the distances between vertexes of one mesh and nearest vertexes of another mesh.

I’ve got about 5000 vertexes in one mesh and 7000 in the other. That gives around 35000000 iterations which isn’t that much. Unity hangs. What can i do?

void Start () {

			float[] d = calculateDistances (mesh1, mesh2);
		
	}

float[] calculateDistances(Mesh cloth, Mesh model)
	{
		Vector3[] vcloth = cloth.vertices;


		Vector3[] vmodel = model.vertices;
		float[] distances = new float[vcloth.Length];



		float lowest_dist = 9999.0f;
		float distance;
		// in case i need the index, better safe than sorry
		int lowest_index = -1;
		Debug.Log (vcloth.Length);
		Debug.Log (vmodel.Length);
		String debug = "";

		for (int i=0; i < vcloth.Length;i++) {

			for(int j=0; j < vmodel.Length;j++){

				// adjust the scale
				distance = (transform.TransformPoint(vcloth _* 0.001f) - transform.TransformPoint(vmodel[j])).magnitude;_
  •  		if (distance < lowest_dist)*
    
  •  		{*
    
  •  			lowest_dist = distance;*
    
  •  			lowest_index = j;*
    
  •  			print (lowest_dist);*
    
  •  		}*
    
  •  	}*
    

distances = lowest_dist;
* lowest_dist = 9999.0f;*

* }*
* Debug.Log (debug);*
* return distances; *
* }*

Yeah, writing to the console in a loop is very slow.

  • Use sqrMagnitude to avoid a square root operation. If you need to know the actual distance at some point, you can do the square root once at the end. You can almost always use this technique when you’re just comparing distance relatively.

  • Do you have to check every vertex against every other vertex? You might be able to create some sort of grid structure over your meshes and find nearest grid cell, then just check the vertices within that grid. Think quad trees.