Memory problems with procedurally generated meshes


I am new to Unity and me and have run into a problem that I can't solve.

I am generating my games terrain procedurally, and storing the meshes for the terrain in several different game objects. I don't use one big mesh because I want to be able to quickly update one part of the mesh at runtime.

I am reusing gameobjects to hold new terrain as you move through the world and I repopulate their meshes with this code:

Mesh mesh = GetComponent<MeshFilter>().mesh;        

mesh.vertices = vertArr;
mesh.normals = normArr;
mesh.uv = texArr;
mesh.triangles = indArr;


This works well, but uses more memory every time I redo the mesh. Looking at the stats window it seems that my VBO total and the ram associated with it is probably the culprit. Looking at the profiler, my mesh number is always the same but the mesh memory increases with the VBO memory.

Is there anyway to get around this? Is assigning mesh.vertices several times just a bad idea?

Thanks for your help!

UPDATE: I followed Jesse's advice and switched to using sharedMesh. It solved my high VBO count problem, but VBO memory still seems to be an issue.

GetComponent().mesh creates a new mesh instance. Use sharedMesh instead. And you only need to run your first line once.

Also, are you sure you need to run these?

mesh.normals = normArr;
mesh.uv = texArr;
mesh.triangles = indArr;

For example, RecalculateNormals() takes care of the first one; unless normArr is just a way for you to change the size of the array. The other two may be necessary, but only if you're doing something that doesn't mimic Unity's heightmap-based terrain engine.

@ConFliX @stevosaurus Hey there, I found my problem was I not nullifying the arrays I used to generate the terrain data and triangles. I went from 6 gigs down to 600 megs, because it was all in GC alloc. I find my meshes not a problem at all even at 1,035,050 triangles for 995 32x32 chunks

For Google’s indexing bots: Unity mesh memory leak problems garbage collection gc alloc mesh triangles help problem procedural procedurally generated terrain