首页 > 解决方案 > 如何从android本地文件夹加载assetBundle?

问题描述

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

我认为网址是错误的。

多次更改 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 文件夹)

标签: c#unity3d

解决方案


你有一个额外的空间

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 处。


推荐阅读