Unity WebGL asset bundle memory is not releasing

As a note, you'll never get this to function as perfectly as you may think. There are utilities for cleaning up garbage and unloading assets but even if you follow all best practices, you still might not get Unity to clean up all the garbage (it does a lot in the background that'll retain allocated memory and there's not much you can do about it). If you're curious about why this is, I'd suggest their writeup on Heap Fragmentation as well as their Memory Optimization Guide.


As far as what you're doing with your specific project, there are at least some improvements you can make:

1) Avoid using the WWW class at all costs. It creates a lot more garbage than it's worth, doesn't always clean up well, and is obsolete in newest versions of Unity. Use UnityWebRequest to download bundles instead.

2) Don't get in the habit of loading a bundle just to load a single asset and then unloading that bundle. If you have lots of loads occurring at runtime, this will cause thrashing and is a fairly inefficient way of managing your bundles. I noticed you're calling bundle.Unload(false) which means the bundle is being unloaded but the loaded prefab asset isn't. I'd suggest restructuring this in a way that you can:

  1. load the bundle you need
  2. load the assets you need from that bundle
  3. wait for the lifetime of all those assets to end
  4. call bundle.Unload(true)

3) Be careful with your call to StopCoroutine(loadBundleRef); (if loadBundleRef is a Coroutine object that is running your web request and bundle loading logic). Interrupting these async operations could lead to memory issues. You should have something in place that ensures web requests and bundle loads either finish completely or, on failure, throw and let your game recover. Don't allow something like StopCoroutine to interrupt them.

4) System.GC.Collect(); is slow and garbage collection happens periodically anyway. Use it sparingly and you might also want to call Resources.UnloadUnusedAssets before calling it.