Search Unity

  1. Check out our Unite Austin 2017 YouTube playlist to catch up on what you missed. More videos coming soon.
    Dismiss Notice
  2. Unity 2017.2 is now released.
    Dismiss Notice
  3. The Unity Gear Store is here to help you look great at your next meetup, user group or conference. With all new Unity apparel, stickers and more!
    Dismiss Notice
  4. Introducing the Unity Essentials Packs! Find out more.
    Dismiss Notice
  5. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice
  6. Unity 2017.3 beta is now available for download.
    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:
    82
    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:
    31,358
    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:
    82
    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:
    31,358
    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:
    82
    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.