AssetBundle Workflow
构建AssetBundles
- 在Project 的面板中选择一个物体
- 在属性面板底部,声明assetboundle的名字,后面是它的后缀,后缀可以是任意的
- 名字可以以路径的方式命名,比如environment/forest,会在environment文件夹生成一个forest文件
Build the AssetBundles
using UnityEditor;
using System.IO;
public class CreateAssetBundles
{
[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);
}
}
Loading AssetBundles and Assets
本地加载资源
For users intending to load from local storage, you’ll be interested in the AssetBundles.LoadFromFile API. Which looks like this:
public class LoadFromFileExample extends MonoBehaviour {
function Start() {
var myLoadedAssetBundle
= AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath, "myassetBundle.ab"));
if (myLoadedAssetBundle == null) {
Debug.Log("Failed to load AssetBundle!");
return;
}
//"MyObject"是打包物体的名字,比如cube打包成assetboundle,名字为“myassetBundle.ab”
var prefab = myLoadedAssetBundle.LoadAsset<GameObject>("MyObject");
Instantiate(prefab);
}
}
网络加载
IEnumerator InstantiateObject()
{
string url = "file:///" + Application.dataPath + "/AssetBundles/" + assetBundleName;
UnityEngine.Networking.UnityWebRequest request
= UnityEngine.Networking.UnityWebRequestAssetBundle.GetAssetBundle(url, 0);
yield return request.Send();
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
GameObject cube = bundle.LoadAsset<GameObject>("Cube");
GameObject sprite = bundle.LoadAsset<GameObject>("Sprite");
Instantiate(cube);
Instantiate(sprite);
}
GetAssetBundle(string, int)
前边是路径,后边是版本号,路径要加上后缀名
UnityWebRequest 处理的是 AssetBundles, DownloadHandlerAssetBundle
, 处理的是assetboundle的请求 request.
来源:https://blog.csdn.net/qq_37672438/article/details/102775797