一个AssetBundle在unity5.5中使用的例子,目标平台是android
以一个胶囊体为例:
1、创建prefab。简单一点,把胶囊体直接放在Assets根目录下:
2、为prefab命名。本例中命名为cab:
3、在Assets同级路径下创建AssetBundle根目录。本例中目录名称为“AssetBundles”。
4、编写生成AssetBundle的代码。代码如下,在Assets目录下创建Editor文件夹,放在里面:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
public class BuildAssetBundle{
[MenuItem("AssetBundle/Build All AssetBundle")]
static void BuildAllAssetBundle() {
string path = "AssetBundles";//相对目录,和Asset同级
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
BuildPipeline.BuildAssetBundles(path, BuildAssetBundleOptions.None, BuildTarget.Android);
//None使用LZMA算法压缩,被压缩的包相比LZ4更多,但是解压时间更久,加载时间更久,解压是必须整体解压
//ChunkBasedCompressor LZ4压缩 可以指定加载具体的资源而无需全部解压
}
}
5、Unity主界面中,点击“AssetBundle/Build All AssetBundle”,生成AssetBundle文件,打开如下:
6、将AssetBundles文件夹拷贝至你网站的根目录下:
7、加载资源,代码如下:
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class MyBehaviour : MonoBehaviour
{
void Start()
{
}
void OnGUI(){
if (GUILayout.Button ("begin",GUILayout.Width(500),GUILayout.Height(300))) {
StartCoroutine(WebRequest());
}
}
IEnumerator WebRequest() {
string cubeURL = "http://XXX.com/yourweb/AssetBundles/cab";
UnityWebRequest request = UnityWebRequest.GetAssetBundle(cubeURL);
yield return request.Send();//发送http请求
if(string.IsNullOrEmpty(request.error)){//没有错误
AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
GameObject cubeWall = ab.LoadAsset<GameObject>("Capsule");//获取prefab
Instantiate(cubeWall, Vector3.zero, Quaternion.identity);//实例化prefab
}else{
yield break;
}
}
}
8、将该脚本绑定在场景中的对象上,执行,点击“begin”,你会发现可以正常加载资源并在零点创建了一个胶囊体对象。