如何从android本地文件夹加载assetBundle?

时间:2019-04-01 09:00:29

标签: c# unity3d

我正在尝试从Unity中从Android文件夹加载AssetBunddle。 但这不起作用...

我认为URL错误。

多次更改URL,推荐或指定Unity文档,但每种情况均失败

这是我的代码。

    public string BundleURL;
    public int version;

    void Start()
    {
        CleanCache();
        BundleURL = "file://"+Application.persistentDataPath + " /BundleTest";

        StartCoroutine(LoadAssetBundle(BundleURL));
        version = 0;
    }

我认为BundleURL错误或有问题

    IEnumerator LoadAssetBundle(string BundleURL)
    {
        //BundleURL = "file://" + path ;
        GameObject obj;
        //ARLog.d ("LoadAssetBundle" + BundleURL);
        while (!Caching.ready)
            yield return null;
        using (WWW www = WWW.LoadFromCacheOrDownload(BundleURL, version))
        {
            yield return www;

            AssetBundle bundle = www.assetBundle;

            String[] mPath = bundle.GetAllAssetNames();
            String bundleName = null;

            if (bundleName != null)
            {
                AssetBundleRequest request = bundle.LoadAssetAsync(bundleName, typeof(GameObject));
                yield return request;

                obj = Instantiate(request.asset) as GameObject;

                bundle.Unload(false);
                www.Dispose();
            }
        } 
    }
}

我要在我的场景中创建实例模型(来自Androind的BundelTest文件夹)

1 个答案:

答案 0 :(得分:1)

您在那里

BundleURL = "file://"+Application.persistentDataPath + " /BundleTest";

" /BundleTest"中!

对于一般的路径,您还是应该使用Path.Combine而不是手动连接字符串:

    BundleURL = Path.Combine(Application.persistentDataPath,"BundleTest");

这可确保在生成的路径中自动为相应的Atrget系统使用正确的路径分隔符(/\)。

要注意的是,WWW已经过时并且发展不快→您应该看看AssetBundle.LoadFromFileAsync,那里有一个使用方法的示例

    public void IEnumerator LoadBundle()
    {
        var bundleLoadRequest = AssetBundle.LoadFromFileAsync(Path.Combine(Application.streamingAssetsPath, "BundleTest"));
        yield return bundleLoadRequest;

        var myLoadedAssetBundle = bundleLoadRequest.assetBundle;
        if (myLoadedAssetBundle == null)
        {
            Debug.Log("Failed to load AssetBundle!");
            yield break;
        }

        var assetLoadRequest = myLoadedAssetBundle.LoadAssetAsync<GameObject>("MyObject");
        yield return assetLoadRequest;

        GameObject prefab = assetLoadRequest.asset as GameObject;
        Instantiate(prefab);

        myLoadedAssetBundle.Unload(false);
    }

如果您更喜欢同步加载结帐AssetBundle.LoadFromFile


一般注意事项:如果您正在使用

using (WWW www = WWW.LoadFromCacheOrDownload(BundleURL, version))
{
    ....
}

您不必使用Dispose,因为它会自动放置在using块的and处。