關於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