MaterialPropertyBlock.SetVectorArray leaking memory.

I’ve encountered an issue when creating MaterialPropertyBlock and assigning two Vector4 arrays to it using SetVectorArray, they never have more than 20k items in them, and the memory usage increases by about 100mb every second or two (so a huge leak).

I have a huge array of few hundred thousand to a million objects, I process the gameplay-related stuff in Burst Job, do a CPU frustum culling down to ~10k that will be displayed on the screen at once, do another Job to create Matrix4x4s and render using Graphics.RenderMeshInstanced(). This works perfectly fine, in standalone builds it uses maybe 70mb of memory and runs at up to 800 fps. I tried to add per-instance color variations based on the state of the object so when calculating Matrix4x4s I also output some Vector4s for the colors and pass them to MaterialPropertyBlock which I assign to my my RenderParams object before the rendering. This causes a huge memory leak as described above. In Memory Profiler this is counted as Native memory and when inspecting it shows Unity Subsystems → Unkown → Unkown. If I remove the SetVectorArray function calls it goes back to the previous sub100mb result even if I still create and assign an empty mpb every frame.

I’m interested in either fixing the leak or finding an alternate solution to what I want to achieve. This is the first time I’m doing anything with Graphics API so please excuse me if I’m missing an obvious solution.

are you creating new material property blocks every time or adjusting the ones over time? it’s optimal to make one at start and change it when nescessary

That category is effectively a bug in how that native memory is assigned to a root in native Unity code. That doesn’t mean it’s necessarily a bug in the memory usage total, but one in attribution that could help figure out if and if so what specifically might be leaking. Please report a bug with a repro project whenever you see that.

If you are using a Unity version older than 2022.2 it might already be fixed on there and if so, there is possibly a reason why it isn’t backported though.

The data changes almost every frame because of the CPU frustum culling and the fact that the displayed objects are dynamic and simulated (e.g the 8th displayed instance will rarely be the same object with the same color). For now I just pre-allocated two Vector4[ ] with 20k items to a single MPB and overwrite the data for every RenderParam before calling RenderMeshInstanced(), this stops the leaking.

This is on 2022.3, I will report the Memory Profiler bug.