- Home /
Native Mesh Access
I'm playing around with a lot of at runtime mesh generation. One of my last big performance hang ups is the GC after rebuilding the mesh frame to frame. Changes to the array sizes associated with the mesh require a new allocation. I could get around allocating new Mesh vert / uv / tri arrays by using some form of buffer. However, the Mesh API doesn't allow expose a count field for either array or access to the underlying native fields.
Has anyone found a way to access the native properties of Mesh or have any ideas on how I could avoid re-allocating verts/tris/uvs when making mesh updates?
Answer by Bunny83 · Sep 22, 2016 at 01:26 AM
In the past the only way around memory allocation was to create the arrays large enough. Left over vertices require space but don't affect performance. The triangle array can also hold more than required elements. When two of the 3 indices are the same the triangle is a degenerate triangle which isn't rendered at all. Of course there is a slight overhead for those triangles but it's almost nothing.
However Unity now introduces the methods: SetVertices, SetIndices and SetTriangles. There are also variants for setting colors and UV coordinates. (For some reason the documentation seems to be currently broken). Those methods take a generic List instead of an array.
Strangely they only implemented "GetUVs" to work with a List instead returning an array. Though setting is much more important anyways ^^.
Thanks for passing along the new setter methods. I finally had a chance to play around with this and unfortunatly it looks like there is still some sort of copy going on under the hood using the setters for vert/ tri/ uv. The meshimplementation around the setVerts method looks like it copies the provided list in some form, since updates to the referenced list after set don't appear to be reflected.
If I construct a vert list reference up front, set the vert list and then cache out the list reference to modify during future frames, the rendered mesh never reflects these changes
//Inside update loop each frame when mesh changes are flagged if (isFirstTimeThrough) { currentVertsList = new List(); mesh.setVertices(currentVertsList); } modifyVerts(currentVertsList);
However if I move the set line out and past the modify line above, so that the set would be called each frame, the mesh does reflect changes since the list contained the updated values when set. The problem I hit now is that there appears to be a major performance impact associated with calling the set, making me think there is another copy happening in unity's native mesh logic.