I am loading and Caching Asset Bundles using below function in unity webgl:
IEnumerator DownloadAndCacheAB(string assetName)
{
// Wait for the Caching system to be ready
while (!Caching.ready)
yield return null;
// Load the AssetBundle file from Cache if it exists with the same version or download and store it in the cache
using (WWW www = WWW.LoadFromCacheOrDownload(finalUrl, 1))
{
yield return www;
if (www.error != null)
{
Debug.Log("WWW download had an error:" + www.error);
}
AssetBundle bundle = www.assetBundle;
if (assetName == "")
{
GameObject abObject = (GameObject)Instantiate(bundle.mainAsset, gameObject.transform.position, gameObject.transform.rotation);
abObject.transform.parent = this.transform;
SetTreeShaderSettings(abObject);
}
else
{
GameObject abObject = (GameObject)Instantiate(bundle.LoadAsset(assetName), gameObject.transform.position, gameObject.transform.rotation);
abObject.transform.parent = this.transform;
}
// Unload the AssetBundles compressed contents to conserve memory
bundle.Unload(false);
} // memory is freed from the web stream (www.Dispose() gets called implicitly)
}
And whenever I want to remove the object i use this function.
public void RemoveBundleObject()
{
//if (www != null)
//{
// www.Dispose();
// www = null;
if (loadBundleRef != null)
{
StopCoroutine(loadBundleRef);
}
if (this.gameObject.transform.childCount > 0)
{
Destroy(this.gameObject.transform.GetChild(0).gameObject);
System.GC.Collect();
}
//}
}
As you can see I am deleting the first child (which I got from asset bundle) then call GC Collect to force garbage collector. but the problem is that my memory is not releasing whenever i unload/destroy the object. Now you will thinking that how i am measuring the memory? I am using WebGLMemoryStats from here. And i am getting this after several iteration of assetbundle load.
Edit: I am using now WebRequest Class to download assetbundle (find here) but still unable to release the memory and sometime get aw snap error.
Even when I am trying to load an empty webgl build again and again its increase the memory heap and then sometime i get aw snap or memory error and chrome crash.
As you can see the initial load is about 1.2 Mb but when i refresh page and take snap shot, it snapshot brings with incremented memory.