1. 创建工具类 Editor/ExportAssetBundles.cs
using System.IO;
using UnityEditor;
public class ExportAssetBundles
{
[MenuItem("Assets/Build AssetBundles")]
static void BuildAllAssetBundles()
{
string assetBundleDirectory = "Assets/AssetBundles";
if (!Directory.Exists(assetBundleDirectory)) {
Directory.CreateDirectory(assetBundleDirectory);
}
BuildPipeline.BuildAssetBundles(assetBundleDirectory, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
}
}
2. 选择 Prefab 文件,在右侧 Inspector 窗口,设置 Bundle name 和 variant。
3. 设置后右键点击选中的 Prefab 文件,在弹出的菜单中点击 Build AssetBundles。
4.程序在 Assets/AssetBundles 中创建了资源目录并且生成了 qart.unity3d 资源包。
5.资源包打好以后可以将其放在本地服务器上,例如:http://localhost/AssetBundles/qart.unity3d。
6.创建入口 MonoBehavior 进行测试:
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class LoadFromFileExample : MonoBehaviour {
private string url = "http://localhost/AssetBundles/qart.unity3d";
void Start() {
Load("Houseboat");
}
public void Load(string watercraftName) {
StartCoroutine(LoadBundle(watercraftName));
}
IEnumerator LoadBundle(string bundleName) {
while (!Caching.ready) {
yield return null;
}
//Begin download
WWW www = WWW.LoadFromCacheOrDownload(url, 0);
yield return www;
//Load the downloaded bundle
AssetBundle bundle = www.assetBundle;
//Load an asset from the loaded bundle
AssetBundleRequest bundleRequest = bundle.LoadAssetAsync(bundleName, typeof(GameObject));
yield return bundleRequest;
//get object
GameObject obj = bundleRequest.asset as GameObject;
Instantiate(obj);
bundle.Unload(false);
www.Dispose();
}
}