Search Unity

Avoid continual array allocation for ComputeBuffer.SetData?

Discussion in 'General Graphics' started by kaffiene, Aug 9, 2018.

  1. kaffiene

    kaffiene

    Joined:
    May 26, 2013
    Posts:
    21
    I'm using ComputeBuffer.SetData(myArray) which takes an array as an input parameter. The number of data items I want in the ComputeBuffer alters per frame but there is no way to tell SetData how many items I want to copy into the buffer. I presume this means the only way to get the right number of items copied is to have myArray created at the required size but this means that as the amount of data I want to copy changes per frame, that I therefore have to allocate that array parameter per frame. My problem is that the array is thousands of elements long and allocating that every frame is creating a tonne of GC that I'd like to avoid. What I'd really like is either a way to slice an array and therefore submit a sub-array that references the original data without copying and with a different size, or be able to do SetData with a number of elements to copy so I would only need to resize my array when the new size exceeded previous maximum.
    Can anyone think of a way around this issue? It seems insane to have to allocate the input array every frame. I feel like there must be something simple I'm missing :)
     
  2. LennartJohansen

    LennartJohansen

    Joined:
    Dec 1, 2014
    Posts:
    2,394
    In 2018.2 there is a NativeArray overload for SetData. That does not make any GC when allocating.