Copying vertices

Hi,

I’m having some problems when copying vertices from one mesh to another.

This works:

new_mesh.vertices = old_mesh.vertices.Clone();

But this don’t:

new_mesh.vertices = new Vector3[old_mesh.vertices.Length];
Array.Copy(old_mesh.vertices, new_mesh.vertices, old_mesh.vertices.Length);

Can someone explain why this is the case? I’m rather new to C# but from what I can tell the Vector3 is a struct so the vertices should be stored as values and not as references in the array.

Thanks!

//ohm

The second one does not work because mesh.vertices=something assigns the array to the mesh.

So what the second snippet does in detail:

  1. creates array of vectors (all set to zeroes initially)
  2. assigns this array to the mesh. Now mesh has all vertex positions at zero.
  3. reads vertices from old mesh and returns the array.
  4. reads vertices from new mesh and returns the array.
  5. copies from the old array into the new array.

At step 5, you have the old vertex data in the array that was returned to your script. But that array is never assigned back to the mesh.

In other words, mesh arrays are get and set “by value”, not “by reference”.

Of course, that make sense.

Thanks!