我正在加载和缓存资产包统一使用以下函数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 来强制垃圾收集器。但问题是,每当我卸载/销毁对象时,我的内存都不会释放。现在你会想我是如何测量内存的?我正在使用 WebGLMemoryStatshere https://github.com/kongregate/Unity-WebGL-Utilities/tree/master/Assets/Plugins/WebGLMemoryStats。
我在多次迭代 assetbundle 加载后得到了这个。
Edit:我现在正在使用 WebRequest 类下载 assetbundle (在这里找到 https://github.com/UnityCommunity/UnityLibrary/blob/master/Assets/Scripts/AssetBundles/AssetBundleLoader.cs)但仍然无法释放内存,有时会出现 aw snap 错误。
即使当我尝试一次又一次地加载空的 webgl 构建时,它也会增加内存堆,然后有时我会收到 aw snap 或内存错误和 chrome 崩溃。
正如您所看到的,初始负载约为 1.2 Mb,但是当我刷新页面并拍摄快照时,它的快照带来了增量内存。