Search code examples
c#unity-game-engineassetbundle

Downloading an AssetBundle more than once fails


I am developing an app in Unity 2017.1.0f3 (for HoloLens if this matters). This app has 3 scenes

  • Scene 1. The user provides credentials and authenticates with a service.
  • Scene 2. The service provides and the app displays a list of resources the user can choose from.
  • Scene 3. After choosing a resource an AssetBundle is downloaded and displayed to the user.

This is the coroutine that downloads the AssetBundle

IEnumerator GetAssetBundle(string assetUrl, Action<AssetBundle> successCallback, Action<string> errorCallback )
    {
        UnityWebRequest request = UnityWebRequest.GetAssetBundle(assetUrl);

        yield return request.Send();

        if (request.isHttpError || request.isNetworkError)
        {
            errorCallback(request.error);
        }
        else
        {
            AssetBundle bundle = ((DownloadHandlerAssetBundle)request.downloadHandler).assetBundle;

            successCallback(bundle);
        }
    }

The user has the ability to go back and forth between the scenes and possibly select the same resource twice. This is when the problem happens.

The first time the user tries to download an AssetBundle all works fine. The second (and all subsequent) time(s) the download fails. The failure is not an error in the download process but that this
((DownloadHandlerAssetBundle)request.downloadHandler).assetBundle; is always null.

I am thinking that Unity will not allow you to download the same AssetBundle more times than one and that you have to cache it once you download it. Is this the case? I would like to avoid that since the app can eventually have a big number of AssetBundles available for download and caching them all once they are downloaded is a bad option.

Do you know of a way to download the same AssetBundle more times than once if needed?


Solution

  • You can unload your bundle individualy:

    bundle.Unload(bool unloadAllLoadedObjects);
    

    or can unload all loaded bundle massive:

    UnloadAllAssetBundles(bool unloadAllObjects);
    

    Take care with the bool unloadAllObjects option, by default is false. If you set to true, all your instantiate assets will be destroyed getting missing references.

    *If you don't know all your loaded bundles you can get an ienumerable list of all loaded bundles: AssetBundle.GetAllLoadedAssetBundles