Unity 加载AssetBundle的几种方式示例

结合Unity官网unity Manual 给出关于AssetBundle的一些加载方法,通过简单示例进行学习总结。
使用Unity版本 unity 2018.4.1 ,其中官网中介绍关于UnityWebRequest加载方式在unity2018中的测试是有问题的,经过研究后已经解决!(unity官网中没有对这块的进行更新)

附上测试代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.Networking;

public class LoadAB : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        // LoadFromFileExample();

        //StartCoroutine(LoadFromMemoryAsync());

        // StartCoroutine(InstantiateObject());

        StartCoroutine(LoadManifest());
    }


    //AssetBundle.LoadFromFile加载方式  用于本地加载
    void LoadFromFileExample() {
        AssetBundle ab = AssetBundle.LoadFromFile(Application.streamingAssetsPath+ "/cube.unity3d");
        if (ab!=null) {
            GameObject cube = ab.LoadAsset("Cube");
            Instantiate(cube);
        }
    }
    //AssetBundle.LoadFromMemoryAsync加载方式  用于本地异步加载
    IEnumerator LoadFromMemoryAsync() {
        AssetBundleCreateRequest createRequest = AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(Application.streamingAssetsPath + "/cube.unity3d"));
        yield return createRequest;
        AssetBundle ab = createRequest.assetBundle;
        if (ab != null)
        {
            GameObject cube = ab.LoadAsset("Cube");
            Instantiate(cube);
        }
    }
    //UnityWebRequest加载方式   既可用于服务器加载也可用于本地加载 
    IEnumerator InstantiateObject() {
        string url = "file:///"+Application.streamingAssetsPath + "/cube.unity3d";  //本地加载  
        // string url = "FTP://192.168.31.168:2121/AssetBundles/cube.unity3d";//服务器加载
        UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url); ;
        yield return request.SendWebRequest();
        AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
        if (ab != null)
        {
            GameObject cube = ab.LoadAsset("Cube");
            Instantiate(cube);
        }

    }


    //使用加载manifest文件方法 加载方式   
    IEnumerator LoadManifest() {
        UnityWebRequest requestManifest = UnityWebRequestAssetBundle.GetAssetBundle("file:///" + Application.streamingAssetsPath + "/StandaloneWindows");
        yield return requestManifest.SendWebRequest();
        AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(requestManifest);
        AssetBundleManifest manifest = assetBundle.LoadAsset("AssetBundleManifest");
        string[] dep = manifest.GetAllDependencies("cube.unity3d");
        AssetBundle[] abs = new AssetBundle[dep.Length];
        for (int i=0;i("Cube");
            Instantiate(cube);
        }
    }
}

测试工程源文件(GitHub)

你可能感兴趣的:(Unity开发)