Version: 5.4
에셋 번들 내부 구조(Asset Bundle Internal Structure)
에셋 번들에서 오브젝트 로드 및 언로드(Loading and unloading objects from an AssetBundle)

에셋 번들 다운로드(Downloading AssetBundles)

섹션에서는 이미 에셋 번들을 빌드하는 방법에 알아보았다고 가정합니다. 그렇지 않은 경우 에셋 번들 빌드를 참조하십시오.

두 가지 방법으로 에셋 번들을 다운로드할 수 있습니다.

  1. Non-caching:WWW object를 사용하여 다운로드합니다. 에셋 번들은 로컬 저장 장치에 있는 Unity의 캐시 폴더에 캐싱되지 않습니다.
  2. Caching: WWW.LoadFromCacheOrDownload 호출을 사용하여 다운로드합니다. 에셋 번들은 로컬 저장 장치에 있는 Unity의 캐시 폴더에 캐싱됩니다. PC/Mac 스탠드얼론 애플리케이션과 iOS/Android 애플리케이션에서는 4GB로 제한됩니다. 다른 플랫폼에 대한 내용은 스크립팅 문서를 참조하십시오.

다음은 논 캐싱 다운로드의 예:

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)
   }
}

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 프로퍼티에 액세스하면 다운로드 된 데이터가 추출되고 에셋 번들 오브젝트가 생성됩니다. 이 때 번들에 포함된 오브젝트를 로드할 준비가 끝납니다. LoadFromCacheOrDownload에 전달되는 두 번째 파라미터는 다운로드할 에셋 번들의 버전을 지정합니다. 에셋 번들이 캐시에 존재하지 않거나 요청된 버전보다 낮을 경우 LoadFromCacheOrDownload가 에셋 번들을 다운로드합니다. 그렇지 않으면 에셋 번들이 캐시에서 로드됩니다.

WWW.LoadFromCacheOrDownload를 사용하여 에셋 번들을 다운로드하는 경우 완료 가능한 에셋 번들 다운로드가 프레임당 하나로 제한됩니다.

모두 통합

컴포넌트가 준비되었으므로 이제 에셋 번들을 로드하고 화면에 콘텐츠를 표시할 씬을 빌드할 수 있습니다.

최종 프로젝트 구조
최종 프로젝트 구조

먼저 __GameObject->CreateEmpty__로 이동하여 빈 게임 오브젝트를 만듭니다. CachingLoadExample 스크립트를 방금 만든 빈 게임 오브젝트로 드래그합니다. 다음, BundleURL 필드에 에셋 번들의 URL을 입력합니다. 오브젝트를 프로젝트 디렉토리 안에 넣었으므로, 파일 디렉토리 위치를 복사하고 file:// 접두사를 추가할 수 있습니다. 예를 들어, file://C:/UnityProjects/AssetBundlesGuide/Assets/AssetBundles/Cube.unity3d

이제 에디터에서 플레이를 누를 수 있습니다. 그러면 큐브 프리팹이 에셋 번들에서 로드되는 것이 보입니다.

에디터(Editor)에서 에셋 번들 로드(Loading)

에디터에서 에셋 번들을 빌드하고 로드해야 하는 작업을 수행하면 개발 프로세스가 느려질 수 있습니다. 예를 들어 에셋 번들의 에셋을 수정하면 에셋 번들를 다시 빌드해야 하고, 프로덕션 환경에서는 모든 에셋 번들이 다함께 빌드될 수 있으므로 에셋 번들 하나를 업데이트하는 프로세스가 길어질 수 있습니다. 에디터에서 에셋 번들로부터 에셋을 로드하는 대신 직접 로드하는 개별 코드 경로를 사용하는 방법이 더 효과적입니다. Resources.LoadAssetAtPath(에디터 전용)를 사용하여 이렇게 할 수 있습니다.

// 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)
에셋 번들에서 오브젝트 로드 및 언로드(Loading and unloading objects from an AssetBundle)