Search Unity

Reading mesh data without Unity making a copy ?

Discussion in 'Scripting' started by theFrenchDutch, Nov 23, 2014.

  1. theFrenchDutch

    theFrenchDutch

    Joined:
    May 5, 2014
    Posts:
    25
    Hello !

    I am working on a procedural planet generator for a school project. So for the dynamic LOD I create meshes in run-time.

    However I have some functions that need to access the data contained in the terrain meshes, like the height of the vertices or the normals to calculate the slope. As that data is only stored in the mesh (keeping it in other arrays would double the memory usage, I'm trying to be as efficient as possible) to access it I was always using meshFilter.mesh.vertices[] or meshFilter.mesh.normals[].

    But then I read something here about how when one does this, Unity creates a copy of the entire array each time you call it. I guess it's a security of some sort but here I'm only reading data, not writing in it, so it seems like a waste of performance.

    I tried using sharedMesh instead (so the call is meshFilter.sharedMesh.vertices[]) but it takes the same amount of time to execute the code, so I guess it's not different ?

    TL-DR : So my question is does Unity really make a copy of the mesh arrays each time you access it even with sharedMesh, and if yes is there a way to avoid it without storing it somewhere else ?

    Thanks for your time :)
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    Yes. ish.
    In order to draw the mesh, the mesh data is sent to the GPU when loaded. In order to perform your own modifications, it needs to be accessible to the CPU. So you need to get a complete copy of the arrays (eg vert positions), change as you need, then set the whole array back to the GPU

    The difference between mesh and sharedMesh is just that it modifies the mesh for all objects that use it.
     
  3. theFrenchDutch

    theFrenchDutch

    Joined:
    May 5, 2014
    Posts:
    25
    Thanks for your answer !

    I get that about needing to work on a copy when you want to change the data, but here I only want to read the data. Is it still necessary to get an entire copy of the arrays to read them ?

    If I understand correctly, the mesh data is sent once to the GPU where it stays and it's the only place it's stored in ? Then even to be able to read it you'd have to retrieve the data from the GPU to the RAM/CPU... Ok, I get it I think.

    Thanks ;)