我正在使用以下函数在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)
}
每当我想要移除对象时,我使用这个函数。
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();
}
//}
}
正如您所看到的,我正在删除第一个子项(从资源包中获取),然后调用GC Collect来强制垃圾收集器。但问题是,当我卸载/销毁对象时,我的内存并没有释放。现在您可能会想,我如何测量内存?我正在使用这里的WebGLMemoryStats。经过几次迭代的assetbundle加载后,我得到了这个结果。
编辑: 我现在正在使用WebRequest类来下载assetbundle(在这里找到),但仍然无法释放内存,有时会出现aw snap错误。
即使我一遍又一遍地尝试加载一个空的webgl构建,它也会增加内存堆,然后有时我会遇到aw snap或内存错误,Chrome崩溃。
正如您所看到的,初始加载大约为1.2 Mb,但当我刷新页面并拍摄快照时,快照会带有增加的内存。
RemoveBundleObject
吗? - derHugo