Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix many memory leaks #486

Merged
merged 2 commits into from
Nov 8, 2024
Merged

Conversation

arthurkehrwald
Copy link
Contributor

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:

  1. Run Unity with the command line option: -diag-job-temp-memory-leak-validation
  2. Preferences > Jobs > Leak Detection Level: Enabled With Stack Trace
  3. Start the game and look at the stack traces of all the leaks (thousands in a few seconds) appear in the console window:
    image

Most of the leaks were caused by field initializers in the PhysicsEngine class. Unity reloads MonoBehaviour classes a lot in edit mode and does not always call the OnDestroy method, which means there is no safe way to deallocate memory allocated using field initializers of MonoBehaviour-derived classes. (You can't use destructors either.) The most obvious workaround would be to use the Awake method for initialization, but that would not necessarily initialize the fields before they are accessed through the public API of the PhysicsEngine, because other MonoBehaviour instances may make calls to this API in their own Awake or OnEnable methods, which can run before the Awake method of PhysicsEngine. Instead, I created the LazyInit class, a generic wrapper for lazy initialization of arbitrary types, and used it to specify how to initialize each native collection member of PhysicsEngine 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.

@freezy
Copy link
Owner

freezy commented Nov 5, 2024

That's awesome, thanks so much. I'll get through all of your PRs by the end of the week, hopefully!

@freezy
Copy link
Owner

freezy commented Nov 8, 2024

@arthurkehrwald can you give me write access to your fork please? Then I'll push a rebased version of this branch to merge.

@freezy freezy force-pushed the fix-many-memory-leaks branch from 8b3d444 to ad647f3 Compare November 8, 2024 14:14
@freezy freezy merged commit 783f203 into freezy:master Nov 8, 2024
3 checks passed
@freezy freezy deleted the fix-many-memory-leaks branch November 8, 2024 14:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants