Ways of modificating mesh triangles

Recently I have been asking about how to modify single vertex or triangle in mesh in topic Optimized vertex manipulation - Questions & Answers - Unity Discussions . As it turned out, there are basically 2 reasonable ways how to do it showed in manual Unity - Scripting API: Mesh , specifically #2 and #3. I don’t clearly get when is using #3 better then #2. In manual is written "Continously changing the mesh triangles and vertices ". I did some experiments and from my sample observation, manipulating triangles using #2 approach works as well and seems to be faster.

int[] triangles = _objectMeshFilter.triangles;
_objectMeshFilter.triangles = triangles;

It seems to me that #3 is only good if I want to change number of vertices or triangles in mesh, other it just creating unnecessary work to garbage collector.
Should I be aware of something using #2 approach ? In what situations should I rather use #3 ?

you’re right, the doco is often badly written! but thank goodness it’s there

what they are getting at:

use 2 if you want to CHANGE the values. so you have 100 verts. later you will still have 100 verts. but you just want to MOVE some of them.

you are GETTING the EXISTING values

var vertices : Vector3 = mesh.vertices; // MAKES A COPY

changing them a bit, and then writing them back to the mesh

mesh.vertices = vertices;

In example three, they mean you are MAKING A WHOLE NEW MESH totally. (it could be an utterly different object.)

where they say “Do some calculations…” they should have written “create an entirely new object in mesh, however you happen to want to do that”

NOTE in example 3, putting it inside Update() is just silly. it is very unlikely (not impossible, but unlikely) a program would come out like that. you’re not going to be building a whole new dragon r whatever in every frame. so that’s just silly.

indeed, in example 2, it is somewhat silly – it’s only in pretty unusual situations, with small objects, you would deform the mesh like that EVERY FRAME.

don’t forget too that COLLDIER MESH is totally different, it is way slow.

and never forget that whenever you type .vertices, it makes A WHOLE COPY … it’s just Special, it’s not like other properties.

hope it helps!

You can modify example #2 from docs to avoid garbage:

using UnityEngine;

public class Example : MonoBehaviour
    Mesh mesh;
    Vector3[] vertices;
    Vector3[] normals;
    void Start()
        mesh = GetComponent<MeshFilter>().mesh;
        vertices = mesh.vertices;
        normals = mesh.normals;
    void Update()
        for (var i = 0; i < vertices.Length; ++i)
            vertices <em>+= normals _* Mathf.Sin(Time.time);_</em>

mesh.vertices = vertices;


mesh.vertices[mesh.triangles[INDEX]] still get a Vector3 of local coordination.