Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The physics engine leaks a lot of memory due to incorrect usage of native collections. This causes the editor to crash a lot. I found the leaks like this:
-diag-job-temp-memory-leak-validation
Most of the leaks were caused by field initializers in the
PhysicsEngine
class. Unity reloadsMonoBehaviour
classes a lot in edit mode and does not always call theOnDestroy
method, which means there is no safe way to deallocate memory allocated using field initializers ofMonoBehaviour
-derived classes. (You can't use destructors either.) The most obvious workaround would be to use theAwake
method for initialization, but that would not necessarily initialize the fields before they are accessed through the public API of thePhysicsEngine
, because otherMonoBehaviour
instances may make calls to this API in their ownAwake
orOnEnable
methods, which can run before theAwake
method ofPhysicsEngine
. Instead, I created theLazyInit
class, a generic wrapper for lazy initialization of arbitrary types, and used it to specify how to initialize each native collection member ofPhysicsEngine
in the field initializer without actually doing it until the member is first accessed. The remaining fixes are self explanatory (using
syntax where possible,try
finally
otherwise).This PR includes the fix proposed in #485.