Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Any approaches C# Struct Caching for Memory and Performance?

Discussion in 'Scripting' started by majeric, Apr 13, 2012.

  1. majeric

    majeric

    Joined:
    Aug 17, 2010
    Posts:
    89
    Is there a good approach to recycling thousands of small structs, a subset of which get modified per frame.

    Take something where i am creating a dynamic mesh on the fly. Some of the vertices and some of the tris get modified but I'd like to be able cache what I have.

    conventionally, I might create an array of these objects and cycle through the array as a primitive factory. Is there any way to encapsulate this in say a generic class or anything?

    I realize that structs are copied by value.

    I'm just not sure what the best performance solution is to this.

    Cheers
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Keep the vertex and triangle arrays, modify whatever you need, and upload them. When you do "mesh.vertices = myVertices", that's actually uploading the vertices to the graphics card. So you don't need a new vertex array every frame, just use the one you already have.

    --Eric
     
  3. majeric

    majeric

    Joined:
    Aug 17, 2010
    Posts:
    89
    Cool... but what about needing to modify the size of my array? The model ad or remove verts as it goes. Is there a clean way of doing this?
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    You can choose a maximum size for the vertex array, and set any unused vertices to Vector3.zero (or any value really as long as it's the same). Those are skipped over when rendered, although they still count toward the upload size.

    --Eric
     
  5. majeric

    majeric

    Joined:
    Aug 17, 2010
    Posts:
    89
    What about structures outside the mesh itself? I have an abstract model is an array of structs. I'm still trying to get a good sense of when I can reasonably use a struct.