Hi Guys,
I’m new to Unity world, and I have read the document for a while.
Today when I read the code snippet blow, I could not figure out why vertices need to write back to mesh.vertices (the last second line).
As I know, in c# array is reference type, so it’s not necessary. Can any one give me hint? Thank you.
Mesh mesh = GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
int i = 0;
while (i < vertices.Length) {
vertices _+= Vector3.up * Time.deltaTime;_
i++;
}
mesh.vertices = vertices;
mesh.RecalculateBounds();
2 Answers
2
When you access Mesh.vertices, that’s a property that returns a copy of the array. Think of Vector3[] vertices = mesh.vertices; as being like Vector3[] vertices = mesh.GetVertices(); where it’s a function that returns Vector3. Unity returns a copy of the vertices from the GPU so you can work on it with the CPU, then uploads it back to the GPU when you set mesh.vertices.
vertices is an array of variable references that is being populated based on mesh.verticies values.
The while statement is calculating the values of those variable for the array.
When setting mesh.vertices = vertices you’re modifying the values of mesh.vertices , which is the target mesh that is being modified to the values from the array.
mesh.vertices may not be a direct attribute of the mesh class but a property. This is why you have to set the property after modifying your array. It's like the transform.position. You can't modify individually each component, you have to get the entire vector into a temporary variable, and set back the position afterwards.
– HelliumYes,
– Owen-Reynoldsmesh.verticesis very much a complex property. It should probably be redone asmesh.setVerts(Vector3[])to emphasize it does much more work than even the average property. The Mesh class is pretty special. If you read other answers, you'll see it's really reaching through the GPU(?) for everything. For example, line 2 of the snippet above is making a copy of the real mesh verts for you to play with (which is very unlike how you'd expect a property to behave) because the actual one isn't directly modifiable.