1.Asset Bundle的打包
和老版本不同的是打包过程简化,打包代码只有下面这一句,但是资源包的名字及后缀名的设置在编辑器的inspector面板底部进行设置
[MenuItem("Assets/Build AssetBundles")] static void BuildAllAssetBundles() { string dir = "AssetBundles"; if( Directory.Exists(dir)==false) { Directory.CreateDirectory(dir); } BuildPipeline.BuildAssetBundles(dir, BuildAssetBundleOptions.UncompressedAssetBundle, BuildTarget.StandaloneWindows64); }
2.Asset Bundle的使用
string path = "AssetBundles/cubewall.unity3d";//资源包存放全路径
第一种加载AB的方式 LoadFromMemoryAsync
本地加载或者通过别的网络请求加载的二进制文件可以直接用 LoadFromMermory进行读取,有异步加载和同步加载两个函数,视情况使用
AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path)); yield return request; AssetBundle ab = request.assetBundle; AssetBundle ab = AssetBundle.LoadFromMemory(File.ReadAllBytes(path));
第二种加载AB的方式LoadFromFile
只能通过本地路径加载
AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(path); yield return request; AssetBundle ab = request.assetBundle;
第三种加载AB的方WWW
老版本的加载方式,可以加载本地资源和远程资源。新老版本都可以使用,但是新版本有新的加载推荐
UnityWebRequest
WWW www = WWW.LoadFromCacheOrDownload(@"http://localhost/AssetBundles/cubewall.unity3d", 1); yield return www; if (string.IsNullOrEmpty(www.error) == false) { Debug.Log(www.error); yield break; } AssetBundle ab = www.assetBundle;
第四种加载AB的方式UnityWebRequest
新的加载方式,官方推荐的新版网络加载
string uri = @"http://localhost/AssetBundles/cubewall.unity3d"; UnityWebRequest request = UnityWebRequest.GetAssetBundle(uri); yield return request.Send(); //AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request); AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
3.新版加载与老版的最大区别
unity5.x之后打包的资源包都有一个资源依赖文件,加载的时候可以根据以来文件进行依赖资源加载,再进行资源加载。
AssetBundle manifestAB = AssetBundle.LoadFromFile("AssetBundles/AssetBundles"); AssetBundleManifest manifest = manifestAB.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
mainfest 就是资源依赖文件
string[] strs = manifest.GetAllDependencies("cubewall.unity3d"); foreach (string name in strs) { print(name); AssetBundle.LoadFromFile("AssetBundles/" + name); }
strs是依赖资源,然后加载出来依赖资源,最后进行使用。
工程资源包:AssetBundle打包和加载