protected IEnumerator InstantiateGameObjectAsync(string assetBundleName, string assetName) { // This is simply to get the elapsed time for this phase of AssetLoading. float startTime = Time.realtimeSinceStartup; // Load asset from assetBundle. AssetBundleLoadAssetOperation request = AssetBundleManager.LoadAssetAsync(assetBundleName, assetName, typeof(GameObject)); if (request == null) { Debug.LogError("Failed AssetBundleLoadAssetOperation on " + assetName + " from the AssetBundle " + assetBundleName + "."); yield break; } // 方案一 // yield return StartCoroutine(request); // 方案二 { while (request.Process() < 0.9f) { // TODO 进度条处理 Debug.Log("加载:" + request.Process() * 100 + "/100"); yield return(new WaitForEndOfFrame()); } while (!request.IsDone()) { Debug.Log("加载:" + request.Process() * 100 + "/100"); yield return(new WaitForEndOfFrame()); } Debug.Log("加载:100/100"); } // Get the Asset. GameObject prefab = request.GetAsset <GameObject> (); // Instantiate the Asset, or log an error. if (prefab != null) { GameObject.Instantiate(prefab); } else { Debug.LogError("Failed to GetAsset from request"); } // Calculate and display the elapsed time. float elapsedTime = Time.realtimeSinceStartup - startTime; Debug.Log(assetName + (prefab == null ? " was not" : " was") + " loaded successfully in " + elapsedTime + " seconds"); }
/// <summary> /// 网络资源加载 /// 异步运行,内部异步加载,获得资源对象,如果资源对象为空,尝试加载,并且通过回调返回加载的资源对象,允许添加加载进度回调 /// </summary> /// <param name="assetBundleName"></param> /// <param name="assetName"></param> /// <param name="loadedListener"></param> /// <param name="progressListener"></param> /// <returns></returns> public IEnumerator LoadAssetObjectCoroutineAsync(string assetName, string assetBundleName, Action <UnityEngine.Object> loadedListener = null, Action <float> progressListener = null) { yield return(null); AssetInfo assetInfo = GetOrAddAssetInfo(assetName, assetBundleName); // 资源已加载 if (assetInfo.AssetObjectCache != null) { if (progressListener != null) { progressListener(1.0f); yield return(null); } if (loadedListener != null) { loadedListener(assetInfo.AssetObjectCache); } } // 资源未加载 else { AssetBundleLoadAssetOperation request = AssetBundleManager.LoadAssetAsync(assetInfo.AssetBundleName, assetInfo.AssetName, typeof(UnityEngine.Object)); if (request == null) { yield break; } // 最多尝试100次(10秒)。防止资源不存在不停下载的情况 TODO 可能有BUG int maxTry = 0; while (request.Process() < 0.9f) { if (request.Process() < 0.001f && maxTry++ > 100) { Debug.LogError("网络无法获得资源:" + assetInfo.AssetBundleName + " " + assetInfo.AssetName); } // TODO 进度条处理 Debug.Log("加载:" + request.Process() * 100 + "/100"); progressListener(request.Process()); yield return(new WaitForSeconds(0.1f)); } while (!request.IsDone()) { maxTry++; Debug.Log("加载:" + request.Process() * 100 + "/100"); progressListener(request.Process()); yield return(new WaitForSeconds(0.1f)); } Debug.Log("加载:100/100"); assetInfo.AssetObjectCache = request.GetAsset <GameObject>(); } }