1. Help us improve the editor usability and artist workflows. Join our discussion to provide your feedback.
    Dismiss Notice
  2. Unity 5.6 is now released.
    Dismiss Notice
  3. Check out all the fixes for 5.5 in patch releases 1 & 2.
    Dismiss Notice
  4. Get further faster with the Unity Plus Accelerator Pack, free for new Unity Plus subscribers for a limited time. Click here for more details.
    Dismiss Notice
  5. Learn how you'll soon be able to publish your games to China in four simple steps with Xiaomi. Sign up now for early access.
    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,003
    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,003
    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.