Memory leaks when hitting play on structures created in custom editor

Hi all.

I have a component that in edit and play mode creates data using a NativeArray and jobs in both modes.

I create it on Start() or whenever I click the editor and it hasn’t been initialized. That way it is created in both editor and play mode.

I dispose all in OnDestroy. In editor I never do, it’s not cheap to destroy and create it all the time, the instance is always there.

If I ever selected the object after having played, (and the array is created in edit mode), whenever I hit play, OnDisable is called for the editor (if it was selected), but either way I get a LEAK . the rest of the process continues. (A Native Collection has not been disposed, resulting in a memory leak. It was allocated)

It is obvious that I’m missing an event right before Play that tells me to dispose all objects created in edit mode that will be created again on play… but I don’t know if there’s any event or any way to do this.

Thanks

I got the answer.

The best solution is to use [ExecuteinEditMode] in the component (be careful with what you’re executing on Update() since it will be executed now in edito mode too).

Then use onEnable and onDisable on the component instead of the editor. That way, disable and enable are called on the component when created, when hitting play mode and when exiting it and you can destroy the data and create it again.

Trying to avoid creating the data all the time will make things complicated. When you select and unselect the object it will still be crated, so It’s fast.