笔者用的版本是Unity3D 5.5.1
注:AssetBundle 可以包含模型,材质,纹理和场景文件等资源。但是 AssetBundle 不能包含脚本。
1.新建Unity3D项目,接着 File -> New Scene 命名 abTest。
2.创建AssetBundles文件夹(放打包资源)、Editor文件夹(放编辑器脚本)、创建Resource文件夹(放预设资源)
Unity3D特殊文件夹参考(
http://www.xuanyusong.com/archives/3229)
3.在层级视图 (Hierarchy)创建一个Cube,并将Cube拖至Resource文件夹。
4.选中Cube预设,在检视面板(Inspector)下方有个AsetBundle选项,点击右侧选项New资源名称(例如:cube)
5.在Editor创建BuildAssetBundle.cs
using UnityEditor;
using UnityEngine;
namespace Assets
{
public class BuildAssetBundle
{
[MenuItem("Custom/Build Asset Bundle")]
static void buildAssetBundle()
{
string str = Application.dataPath + "/AssetBundles";
//打包资源路径(参数1:资源保存路径 参数2:未了解 参数3:选择平台,各个平台间不能混用)
BuildPipeline.BuildAssetBundles(str, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
}
}
}
通过编辑器打包生成AssetBundle资源
6.接下来就是创建资源加载脚本 LoadAssetBundle.cs
using UnityEngine;
using System.Collections;
public class LoadAssetBundle : MonoBehaviour
{
private GameObject curObj;
private string filePath = "";
private string ObjName = "cube";
void Start()
{
filePath = "file://" + Application.dataPath + "/AssetBundles/" + ObjName;
StartCoroutine(GetAssetBundleObj(filePath));
}
IEnumerator GetAssetBundleObj(string filePath)
{
WWW www = new WWW(filePath); //利用www类加载
yield return www;
AssetBundle curBundleObj = www.assetBundle; //获得AssetBundle
AssetBundleRequest obj = curBundleObj.LoadAssetAsync(ObjName, typeof(GameObject)); //异步加载GameObject类型
yield return obj;
curObj = Instantiate(obj.asset) as GameObject;
curObj.name = "cube";
yield return null;
curBundleObj.Unload(false); //卸载所有包含在bundle中的对象,已经加载的才会卸载
//www.Dispose(); //Unity官方的角度已不再推荐使用Dispose()。官方例子也没有了Dispose()
}
}
7.将LoadAssetBundle脚本拖至Camera,然后运行程序。