我已更新到Unity 2017.1。当我从捆绑实例化场景中的对象时,应用程序会冻结1-3秒。我之前的Unity版本没有注意到这个问题,但我不想降级到5.6。
IEnumerator LoadAssetBundle(WWW www)
{
EventLisaner.Instance.SetAudioStation(false);
while (!www.isDone)
{
int current = (int)(www.progress * 100);
progressText.text = string.Format("Загрузка модели {0}%", current.ToString());
yield return null;
}
yield return www;
if (www.error == null)
{
if (bundle != null)
{
Destroy(destroyBundle);
bundle.Unload(true);
}
bundle = www.assetBundle;
StartCoroutine(InstantiationBundle());
}
else
{
loaderUI.SetActive(false);
}
}
private IEnumerator InstantiationBundle()
{
GameObject inst = bundle.LoadAsset("prefab") as GameObject;
GameObject obj = Instantiate(inst);
obj.transform.SetParent(RayCam.selectObj.transform.parent, false);
obj.AddComponent<VuforiaMove>();
loaderUI.SetActive(false);
destroyBundle = obj;
EventLisaner.Instance.enabledLoadBundle = true;
EventLisaner.Instance.enbledNextTrekingDonload = true;
yield return null;
}
UPD:我已经确定此行上出现了错误:bundle = www.assetBundle;
。我试过yield return bundle = www.assetBundle;
,但它似乎没有帮助。仍然有冻结。
答案 0 :(得分:2)
导致此冻结的唯一代码行是bundle.LoadAsset
。这是在主线程中加载和反序列化AssetBundle。您必须使用此函数的异步版本LoadAssetAsync
然后将其生成以完成加载。它将在另一个线程中进行加载。协程只是用来等待在另一个线程中执行的操作完成。
替换
GameObject inst = bundle.LoadAsset("prefab") as GameObject;
与
AssetBundleRequest request = bundle.LoadAssetAsync("prefab");
//Wait for load
yield return request;
GameObject inst = request.asset as GameObject;
其余的代码应该是相同的。
修改强>:
如果www.assetBundle
导致问题,请删除该行代码并使用AssetBundle.LoadFromMemoryAsync(www.bytes)
加载Assetbundle。您必须将WWW
传递给InstantiationBundle
函数。
private IEnumerator InstantiationBundle(WWW www)
{
AssetBundleCreateRequest createRequest = AssetBundle.LoadFromMemoryAsync(www.bytes);
yield return createRequest;
AssetBundle bundle = createRequest.assetBundle;
AssetBundleRequest request = bundle.LoadAssetAsync("prefab");
//Wait for load
yield return request;
GameObject inst = request.asset as GameObject;
....
.....
yield return null;
}