Unity在Mesh更新的时候会增加内存,一般的方法是使用数组去填入。


        Vector3[] vertices = new Vector3[segmentCount * 4];
        Vector3[] normals = new Vector3[segmentCount * 4];
        Vector4[] tangents = new Vector4[segmentCount * 4];
        Color[] colors = new Color[segmentCount * 4];
        Vector2[] uvs = new Vector2[segmentCount * 4];
        int[] triangles = new int[segmentCount * 6];

        mesh.vertices = vertices;
        mesh.normals = normals;
        mesh.tangents = tangents;
        mesh.triangles = triangles;
        mesh.colors = colors;
        mesh.uv = uvs;

这样子既要每次申请内存,操作起来也不很方便。

之后在一个帖子上看到

http://answers.unity3d.com/questions/1102650/avoiding-gc-when-rebuilding-meshuv-and-meshvertice.html

其实可以用list

这样只要一开始申请足够内存就不需要一直申请了。


    private List _vertices = new List(1024);
    private List _normals = new List(1024);
    private List _tangents = new List(1024);
    private List _colors = new List(1024);
    private List _uvs = new List(1024);
    private List _triangles = new List(1024);

        mesh.SetVertices(_vertices);
        mesh.SetNormals(_normals);
        mesh.SetTangents(_tangents);
        mesh.SetTriangles(_triangles,0);
        mesh.SetColors(_colors);
        mesh.SetUVs(0,_uvs);