I have a simple procedurally generated mesh, with uvs that tile correctly

for(int i=1; i<vertices; i++) {
    uv[i] =  new Vector2(x,z);  //pseudocode
mesh.uv = uv;

This works fine. However if I later attempt to change one of the mesh.uv entries

for(<loop over four nodes on tile>) {
    Debug.Log("before: " + mesh.uv[vertex_index].ToString()); // print before

    mesh.uv[vertex_index] =  new Vector2(new_x,new_y);

    Debug.Log("after: " + mesh.uv[vertex_index].ToString()); // print after

I get no change in mesh.uv.

What am I missing about unity mesh storage? This works fine for a simple array of Vector2:

Vector2[] v2 = {Vector2.one, Vector2.one};
for (int j = 0; j < 2; j++) {
    v2[j] = new Vector2(2,3);

EDIT: I can make a successful uv-change by making a copy of the mesh.uv, changing the Vector2 values in the copy and then assigning mesh.uv = copy.

Vector2[] uvCopy = mesh.uv;
for(changed vertices) {
    uvCopy[vertex_index] = new Vector2(new_x, new_y);
mesh.uv = uvCopy;

I still would like to know what was wrong with my original approach, if anyone has any ideas.

  • \$\begingroup\$ Post the output. \$\endgroup\$ – Ben Nov 20 '14 at 9:48
  • \$\begingroup\$ before: (0.3, 1.0) after: (0.3, 1.0); Expected: (2,3). No change and no errors. The array of Vector2 performs as expected, (1,1) goes to (2,3) \$\endgroup\$ – NexD Nov 20 '14 at 10:01

I'm fairly certain, though someone will no doubt prove me wrong, that you can not change individual elements in the mesh arrays of vertices, triangles, uvs etc. That is why when you work with procedural meshes you always update the entire array at once when you've finished modifying it.

The reason for this is that mesh.uv gives you a copy of the mesh uvs array or assigns the uvs array, it doesn't allow you to directly modify individual uvs because you're not actually modifying the uvs on the mesh, you're modifying a copy.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.