关于unity中Assetbundle动态加载,刚刚在网上学了一点,现在就分享给大家,亲测有用
a.将脚本ExportAssetBundles.cs放到Editor文件夹下(没有可以新建),会在asset菜单下新增两个功能键(也可以在脚本中直接调用)
ExportAssetBundles脚本的代码:
using UnityEngine; using System.Collections; using UnityEditor; public class ExportAssetBundles : Editor { //在Unity编辑器中添加菜单 [MenuItem("Assets/Build AssetBundle From Selection")] static void ExportResourceRGB2() { // 打开保存面板,获得用户选择的路径 string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "assetbundle"); if (path.Length != 0) { // 选择的要保存的对象 Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets); //打包 BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, BuildTarget.StandaloneWindows); } } [MenuItem("Assets/Save Scene")] static void ExportScene() { // 打开保存面板,获得用户选择的路径 string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d"); if (path.Length != 0) { // 选择的要保存的对象 Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets); // 注意此处要保存的场景位于Assets目录下的Scenes文件夹下,可视情况而定 string[] scenes = { "Assets/Scenes/Scene1.unity" }; //打包 BuildPipeline.BuildPlayer(scenes, path, BuildTarget.StandaloneWindows, BuildOptions.BuildAdditionalStreamedScenes); } } }
b.分别选中资源和场景点击Assets菜单最下方的打包资源和场景选项,自由选择路径与名称,只要在加载脚本bundleLoad.cs中对应即可
bundleLoad脚本为:
using UnityEngine; using System; using System.Collections; public class bundleLoad : MonoBehaviour { //注意资源链接 private string BundleURL = "file:///E:/UnityTest/MapTest1/mapTest1/cube.assetbundle"; private string SceneURL = "file:///E:/UnityTest/Scene1.unity3d"; void Start() { //BundleURL = "file//"+Application.dataPath+"/cube.assetbundle"; Debug.Log(BundleURL); StartCoroutine(DownloadAssetAndScene()); } IEnumerator DownloadAssetAndScene() { //下载assetbundle,加载Cube using (WWW asset = new WWW(BundleURL)) { yield return asset; //AssetBundle bundle = asset.assetBundle; //AssetBundle bundle = (AssetBundle)DownloadAsset.assetBundle.LoadAsset(asset); //bundle.LoadAll(); Instantiate(asset.assetBundle.mainAsset); asset.assetBundle.Unload(false); yield return new WaitForSeconds(3); } //下载场景,加载场景 using (WWW scene = new WWW(SceneURL)) { yield return scene; AssetBundle bundle = scene.assetBundle; //bundle.Load(); //注意场景名称 Application.LoadLevel("Scene1"); } } }
c.新建场景,将加载脚本挂在场景主相机或者课执行的对象上使脚本运行
希望对初学者有帮助
参考资料:
1.http://www.xuanyusong.com/
2.http://game.ceeger.com/Manual/DownloadingAssetBundles.html