AssetBundle的初步使用
资源下载
AssetBundle是unity提供的一种用于存储资源的文件格式,它可以存储任意一种Unity引擎能够识别的资源,例如模型、纹理、音频、动画片段甚至整个场景等。同时,AssetBundle也可以包含开发者自定义的二进制文件,只需将二进制文件的后缀名改成“.bytes”,Unity引擎即可将其识别为TextAsset,进而可以被打包到AssetBundle文件中。
用户可以通过AssetBundle的UI和简单的脚本在Unity中创建AssetBundle文件,Unity引擎提供了二种创建AssetBundle的API,分别如下:
BuildPipeline.BuildAssetBundles
通过该接口,开发者可以将编辑器中指定的Assets打包。
BuildPipeline.BuildPlayer
通过该接口,开发者可以将场景编译成播放器。
AssetBundle的打包
在unity文件夹下面的Editor文件夹里面创建 ExportAsset用来打包。
using UnityEngine;
using System.Collections;
using UnityEditor;
public class ExportAsset : MonoBehaviour {
[MenuItem("Export Editor/Build AssetBundles")]
static void CreateAssetBundlesMain()
{
BuildPipeline.BuildAssetBundles("Assets/AssetBundles");
}
}
菜单就会出现下面的样子
将Prefab制作成AssetBundle
这个是制作成sphere的assetBundle的,在预览窗口里面的none改成sphere,就是这个时候我们设置了一个叫做sphere的assetBundle了。
我们在这块一共打包了两个物体。一个Cube,还有个Sphere。
我们这里将纹理(texture),材质(material)一同打包了。
看下总的AssetBundle.manifest 文件,就可以得到打包的结构。
用下面的图来看结构就清楚多了。
生成物体,加载依赖
我们使用的是本地加载,所以,将物体打包好之后,只需要放在Asset文件夹下面就可以了。
在Hierchy面板中添加个空的物体,给它添加脚本,或者直接给摄像机添加脚本就可以了。
先加载总的manifest文件
WWW wwwManifest = new WWW(manifestPath);
获取相关依赖文件列表
//解压
AssetBundle manifestBundle = wwwManifest.assetBundle;
AssetBundleManifest manifest = (AssetBundleManifest) manifestBundle.LoadAsset("AssetBundleManifest");
manifestBundle.Unload(false);
//获取依赖文件列表,只是列表,不是文件
string[] dependentAssetBundles = manifest.GetAllDependencies(assetBundleName);
加载所有相关依赖文件;
for (int i = 0; i < dependentAssetBundles.Length; i++)
{
//加载所有依赖文件
WWW www = new WWW(assetBundlePath + dependentAssetBundles[i]);
//WWW.LoadFromCacheOrDownload(assetBundlePath + dependentAssetBundles[i], 0);
yield return www;
abs[i] = www.assetBundle;
}
加载目标资源;
//加载需要的文件
WWW wwwSphere = new WWW(assetBundlePath + assetBundleName);
//WWW.LoadFromCacheOrDownload(assetBundlePath + assetBundleName, 0);
yield return wwwSphere;
AssetBundle assetBundle = wwwSphere.assetBundle;
WWW wwwCube =new WWW(assetBundlePath + "Cube");
//WWW.LoadFromCacheOrDownload(assetBundlePath + "Cube", 0);
yield return wwwCube;
AssetBundle assetBundle1 = wwwCube.assetBundle;
//加载资源
GameObject gSphere = assetBundle.LoadAsset("Sphere") as GameObject;
GameObject gCube = assetBundle1.LoadAsset("Cube") as GameObject;
实例化和卸载
if (gSphere != null && gCube != null)
{
//实例化
Instantiate(gSphere);
Instantiate(gCube);
assetBundle.Unload(false);
assetBundle1.Unload(false);
}
这样子整个加载就完成了。