AssetBundle加载资源的过程

参考:http://blog.csdn.net/jason_520/article/details/54616953

AssetBundle加载资源的过程

1、加载总Manifest文件;
2、获取相关依赖文件列表;
3、加载所有相关依赖文件;
4、加载目标资源;
5、卸载所有相关依赖文件。

参考代码如下:

 IEnumerator LoadAsset()
    {
        //首先加载总Manifest文件;    
        WWW wwwAll = new WWW(BundleURL+ "StreamingAssets");
        yield return wwwAll;
        if (!string.IsNullOrEmpty(wwwAll.error))
        {
            Debug.LogError(wwwAll.error);
        }
        else
        {
            AssetBundle ab = wwwAll.assetBundle;
            AssetBundleManifest manifest = (AssetBundleManifest)ab.LoadAsset("AssetBundleManifest");
            ab.Unload(false);

            //获取依赖文件列表;    
            string[] depends = manifest.GetAllDependencies("cube.unity3d");
            AssetBundle[] dependsAssetBundle = new AssetBundle[depends.Length];

            for (int index = 0; index < depends.Length; index++)
            {
                //加载所有的依赖文件;    
                WWW dwww = WWW.LoadFromCacheOrDownload(BundleURL + depends[index], 0);
                yield return dwww;
                dependsAssetBundle[index] = dwww.assetBundle;
            }

            //加载我们需要的文件;    
            WWW www = new WWW(BundleURL + "cube.unity3d");
            yield return www;
            if (!string.IsNullOrEmpty(www.error))
            {
                Debug.LogError(www.error);
            }
            else
            {
                AssetBundle assetBundle = www.assetBundle;

                AssetBundleRequest request = assetBundle.LoadAssetAsync("cube", typeof(GameObject));

                // Wait for completion
                yield return request;

                // Get the reference to the loaded object
                GameObject obj = request.asset as GameObject;

                Instantiate(obj);

                assetBundle.Unload(false);
            }

            //卸载依赖文件的包    
            for (int index = 0; index < depends.Length; index++)
            {
                dependsAssetBundle[index].Unload(false);
            }
        }
    }

你可能感兴趣的:(Unity3D)