Create and update mesh

Hi everyone,

I’m trying to implement a class where i handle the mesh creation of a triangle.
I’ve a question about the vertices update of my mesh, i don’t understand why i need to initialize the vertex array instead of change the value of each vertex.

        // -------------- WORK--------------
        mesh.vertices = new Vector3[] { new Vector3(0, 0, 0 )+ position,
                                            ( new Vector3(0, 1 * scale.y, 0) + position ) ,
                                               ( new Vector3(1 * scale.x, 1, 0) + position)
                                    };
        //------------------------------------------------//

        // -------------- Doesn't work --------------
        mesh.vertices[0] = new Vector3(0, 0, 0) + position;
        mesh.vertices[1] = new Vector3(0, 1 * scale.y, 0) + position;
        mesh.vertices[2] = new Vector3(1 * scale.x, 1, 0) + position;
        //------------------------------------------------//

Because mesh.vertices returns a copy of the array, so changing its contents doesn’t do anything unless you assign the array copy back to the original when you’re done. If you’re asking why they chose to make it return a copy, I assume there’s more going on in the mesh’s vertex-array property setter than just a single assignment, and they don’t want you to be able to bypass that.

1 Like

The Mesh.vertices documentation says:

“Returns a copy of the vertex positions or assigns a new vertex positions array.”

So it does not work when you are directly accessing the vertices, because you are modifying the copy version of the array, not the original. So the way to go is to get a copy of the array, modify it and then assign the array as a whole back to the mesh.