Post before edit: -----------------------
I have a compute buffer declared as such
[SerializeField, HideInInspector]
public ComputeBuffer _append;
However, it becomes null, even with SerializeField, after the code hotswaps.
The issue is that during hotswap, the “OnDestroy” method is not called, and therefore I don’t Dispose/Release() the buffers, causing a memory leak.
I can’t be 100% sure that this is the cause of a memory leak I have, but sure enough, quickly running and stopping the game does not permanently increase the memory usage of the editor (as measured by the Task Manager), meanwhile running, hotswapping and stopping does.
I’ve tried using OnBeforeSerialize, but there is no way to know if this was called because I clicked the GameObject (and thus the inspector called OnBeforeSerialize), or if it was the unity serialization.
I don’t believe you can serialize ComputeBuffers like this, as they are not UnityObjects. It wouldn’t really make sense to. Hotswapping is a bit of a nightmare to detect and I avoid it like the plague personally, however you can poll EditorApplication.isCompiling to try and chuck in a sneaky Dispose(). Personally I just create and dispose them as close to use as possible to avoid this issue, but a ComputeBufferPool sort of thing would work as well.
I was experimenting with checking Event.current == null && isTheStackTraceJustThisMethod() inside the serialization callback, and while this does work, unfortunately, checking a combo box on a inspector window is detected as a false positive
I am currently investigating using a wrapper that overrides Finalize, then I just release the buffer right before the wrapper gets GC’ed. Hopefully it will work, but I still did not have the time to test it.
If I could just instantiate a compute buffer through it’s native pointer, then all would work (at least it seems), I could just serialize the pointer and use it, since obviously the buffer still exists in the graphics card memory.
UnityEditor.AssemblyReloadEvents.beforeAssemblyReload also solves Compute Buffers from URP Custom Render Passes throwing GC warnings. Thanks for sharing your solution here.