unity 之 AssetBoundle

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 14:54:28

AssetBundle Workflow

构建AssetBundles

  1. 在Project 的面板中选择一个物体
  2. 在属性面板底部,声明assetboundle的名字,后面是它的后缀,后缀可以是任意的
  3. 名字可以以路径的方式命名,比如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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!