Morphing and garbage collection

Hi I have a project where I have a lot of morphed objects. So each frame I am (as the documentation says to) reading the current vertices from the mesh, updating them and then writing them back to the mesh. Same with the normals. This works perfectly and gives the result I want.

The problem is that each frame I am creating the number of vertices worth of Vector3’s x4 (Two source meshes each with vertices and normals). As the number of morphing objects goes up I am finding that the garbage collector shows as quite large spikes in the Inspector as it cleans up these objects and is having a noticeable effect on the performance of my application - making it slightly jerky.

What I would like to do is basically edit the vertices of the mesh directly rather than having to work on a copy of the vertices returned by Mesh.vertices which is discarded each frame.

 v0  = m_Meshes[srcIndex].vertices; // these verts are a copy
   n0  = m_Meshes[srcIndex].normals;// these norms are a copy
   v1  = m_Meshes[dstIndex].vertices;// these verts are a copy
   n1  = m_Meshes[dstIndex].normals;// these norms are a copy
   
   for (i=0; i<vdst.Length; i++)
   {
      vdst[i] = Vector3.Lerp(v0[i], v1[i], t);
	  ndst[i] = Vector3.Lerp(n0[i], n1[i], t);
	}

   m_Mesh.vertices = vdst;
   m_Mesh.normals = ndst;
   m_Mesh.RecalculateBounds();

Thanks in advance
Tom Mulder

The mesh’s vertices array is actually a property that executes some code as it is used, so there isn’t a way to access individual vertices in isolation (and the same goes for normals, etc). For most purposes, you don’t need to get the value of the vertices and normals properties each frame. You can just use your own arrays, make changes to them and assign them to the appropriate mesh properties. This will save the overhead of retrieving the properties and also reduce the amount of memory garbage generated.

Andeee you are awesome! I’ll try that. Should really have thought of that but never mind…

I created a class that takes in a mesh and stores the vertices and normals. So instead of reading the vertices and normals each frame from the source meshes for the morph, I just access them from the corresponding class. So no more spawned vector3’s each frame.

class MeshData
{
	var vertices : Vector3[];
	var normals : Vector3[];
	
	public function MeshData(mesh : Mesh)
	{
		vertices = mesh.vertices;
		normals = mesh.normals;
	}	
}