Version: 5.4
Asset Bundle Internal Structure
Загрузка и выгрузка объектов из AssetBundle

Скачивание AssetBundles

Для понимания этого раздела, нужно чтобы вы уже освоили процесс сборки Asset Bundles. Если вы этого еще не сделали, тогда, пожалуйста, ознакомьтесь со следующим материалом: Сборка AssetBundles

Есть два способа скачивания AssetBundle

  1. Без кэширования: Это делается с использованием нового объекта WWW. AssetBundles не кэшируются в папке кэша Unity на локальном устройстве хранения.
  2. С Кэшированием: Для этого нужно вызвать WWW.LoadFromCacheOrDownload. AssetBundles кэшируются в папке кэша Unity на локальном устройстве хранения. Общий кэш в WebPlayer позволяет хранить до 50 MB кэшированных AssetBundles. PC/Mac Standalone приложения и iOS/Android приложения ограничиваются 4 GB кеша. WebPlayer приложения, которые используют выделенный кэш, ограничены количеством байтов, указанных в лицензионном соглашении о кэше.

Ниже приведен пример скачивания без кэширования

using System;
using UnityEngine;
using System.Collections; class NonCachingLoadExample : MonoBehaviour {
   public string BundleURL;
   public string AssetName;
   IEnumerator Start() {
     // Download the file from the URL. It will not be saved in the Cache
     using (WWW www = new WWW(BundleURL)) {
         yield return www;
         if (www.error != null)
             throw new Exception("WWW download had an error:" + www.error);
         AssetBundle bundle = www.assetBundle;
         if (AssetName == "")
             Instantiate(bundle.mainAsset);
         else
             Instantiate(bundle.LoadAsset(AssetName));
                   // Unload the AssetBundles compressed contents to conserve memory
                   bundle.Unload(false);

     } // memory is freed from the web stream (www.Dispose() gets called implicitly)
   }
}

Рекомендуется скачивать AssetBundles с помощью WWW.LoadFromCacheOrDownload. Например:

using System;
using UnityEngine;
using System.Collections;

public class CachingLoadExample : MonoBehaviour {
    public string BundleURL;
    public string AssetName;
    public int version;

    void Start() {
        StartCoroutine (DownloadAndCache());
    }

    IEnumerator DownloadAndCache (){
        // Wait for the Caching system to be ready
        while (!Caching.ready)
            yield return null;

        // Load the AssetBundle file from Cache if it exists with the same version or download and store it in the cache
        using(WWW www = WWW.LoadFromCacheOrDownload (BundleURL, version)){
            yield return www;
            if (www.error != null)
                throw new Exception("WWW download had an error:" + www.error);
            AssetBundle bundle = www.assetBundle;
            if (AssetName == "")
                Instantiate(bundle.mainAsset);
            else
                Instantiate(bundle.LoadAsset(AssetName));
                    // Unload the AssetBundles compressed contents to conserve memory
                    bundle.Unload(false);

        } // memory is freed from the web stream (www.Dispose() gets called implicitly)
    }
}

Когда вы обращаетесь к свойству .assetBundle, скачанные данные извлекаются, а также создается объект AssetBundle. Теперь вы готовы к тому, чтобы загрузить объекты, содержащиеся в AssetBundle. Второй параметр, который передается LoadFromCacheOrDownload, указывает какую версию AssetBundle нужно скачать. Если AssetBundle нет в кэше или версия ниже запрашиваемой, LoadFromCacheOrDownload скачает AssetBundle, в противном случае AssetBundle будет загружен из кэша.

Please note that only up to one AssetBundle download can finish per frame when they are downloaded with WWW.LoadFromCacheOrDownload.

Собираем все воедино

Now that the components are in place you can build a scene that will allow you to load your AssetBundle and display the contents on screen.

Final project structure
Final project structure

Сначала создайте пустой игровой объект, для этого переходим по GameObject->CreateEmpty. Перетащите скрипт CachingLoadExample на только что созданный пустой игровой объект. После этого впишите Url того AssetBundle, который нужно скачать в поле BundleURL. Поскольку у нас bundle находится в папке проекта, вы можете скопировать путь к этой папке и приписать к нему спереди file://, например,file://C:/UnityProjects/AssetBundlesGuide/Assets/AssetBundles/Cube.unity3d

You can now hit play in the Editor and you should see the Cube prefab being loaded from the AssetBundle.

Загрузка AssetBundles в Редакторе

When working in the Editor requiring AssetBundles to be built and loaded can slow down the development process. For instance, if an Asset from an AssetBundle is modified this will then require the AssetBundle to be rebuilt and in a production environment it is most likely that all AssetBundles are built together and therefore making the process of updating a single AssetBundle a lengthy operation. A better approach is to have a separate code path in the Editor that will load the Asset directly instead of loading it from an AssetBundle. To do this it is possible to use Resources.LoadAssetAtPath (Editor only).

// C# Example
// Loading an Asset from disk instead of loading from an AssetBundle
// when running in the Editor
using System.Collections;
using UnityEngine;

class LoadAssetFromAssetBundle : MonoBehaviour
{
    public Object Obj;

    public IEnumerator DownloadAssetBundle<T>(string asset, string url, int version) where T : Object {
        Obj = null;

#if UNITY_EDITOR
        Obj = Resources.LoadAssetAtPath("Assets/" + asset, typeof(T));
        yield return null;

#else
        // Wait for the Caching system to be ready
        while (!Caching.ready)
            yield return null;

        // Start the download
        using(WWW www = WWW.LoadFromCacheOrDownload (url, version)){
            yield return www;
            if (www.error != null)
                        throw new Exception("WWW download:" + www.error);
            AssetBundle assetBundle = www.assetBundle;
            Obj = assetBundle.LoadAsset(asset, typeof(T));
            // Unload the AssetBundles compressed contents to conserve memory
            bundle.Unload(false);

        } // memory is freed from the web stream (www.Dispose() gets called implicitly)

#endif
    }
}

Asset Bundle Internal Structure
Загрузка и выгрузка объектов из AssetBundle