본문 바로가기

develop

[Unity] Assetbundle 사용하기

 Unity3d 엔진을 활용해서 모바일에서 데이터를 쓰려면 결국 Assetbundle을 사용해야 한다. 이유는 용량 때문이다. 디바이스에 맞는 마켓에서 게임을 다운 받을 때 큰 용량을 다운로드 한다면, 시간이 오래 걸리고 사용자가 이탈할 확률이 높기 때문이다. 그리고 특히 잦은 패치를 해야하는 어플리케이션은 Assetbundle을 꼭 사용해야 좋다.


 Assetbundle을 ios나 android 버전으로 만드는 것은 간단하다.

[MenuItem ( "Assets/Build AssetBundle From Selection Android - Track dependencies" )]
static void ExportResourceToAssetBundle ()
{
    string FilePath = EditorUnity.SaveFilePanel ( "Export Projet Data", "", "NewAssetBundle", "unity3d" );

    if ( FilePath.Length != 0 )
    {
        Object[] ProjSelection = Selection.GetFiltered ( typeof ( Object ), SelectionMode, DeepAssets );
        BuildPipeline.BuildAssetBundle ( Selection.activeObject, ProjSelection, FilePath, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, BuildTarget.Android );
        Selection.objects = ProjSelection;
    }
}

 상기 코드는 가장 간단하게 Assetbundle을 만드는 것이다. 여기에서 android와 ios 버전을 바꾸는 것은 BuildPipeline.BuildAssetBundle의 마지막 옵션인 BuildTarget.Android만 BuildTarget.IOS로 바꾸면 된다.

 상기 코드는 메뉴의 asset항목에 Build AssetBundle From Selection Android - Track dependencies라는 항목을 추가한다. 그리고 Assetbundle을 만들 prefab을 선택한 뒤, 해당 항목을 선택하면 assetbundle을 만들 경로와 파일명을 설정하고 생성한다.

 상기 코드에서는 기본 확장자를 unity3d로 설정했는데, Assetbundle을 만들 때 확장자는 자유롭게 설정할 수 있다.


 이렇게 만들어진 Assetbundle을 사용하는 방법을 알아보자.


 Assetbundle은 서버에 올려두고 읽어 와서 사용하는게 일반적이다. 물론 어플리케이션에 넣고 참조해도 된다. Assetbundle을 서버에 올려둔 뒤 읽어 오려면 WWW 클래스를 사용한다. ( 참고로 WWW 클래스는 unity3d 엔진에서 파일을 로드하는 객체이다 )

WWW www = new WWW ( urlOfAssetbundle );

 상기 코드에서 urlOfAssetbundle은 http://로 시작하면 웹에서 읽어 오고, file://로 시작하면 어플리케이션 내부에서 읽어 온다. 그리고 중요한 것은 아직 파일이 생성되지 않고 읽어 오기만 한 상태라는 것이다.


 그렇다면 파일로 저장하는 방법을 알아보자.


 C#이라면 StreamWriter / StreamReader를 이용하면 된다. 여기서 주의할 점은 ios는 Application.dataPath 안에 /Documents/ 안에만 저장할 수 있다는 것이다. android는 sd카드에 받을 수 있는데 이 때 경로는 mnt/sdcard/이다.

 참조한 assetbundle은 GameObject.Instantiate 함수로 prefab을 게임에 생성한다든지, string patchlist = www.data; 이런 방식으로 텍스트 파일일 경우 내부 데이터를 쓴다든지 할 수 있다.

 각각의 assetbundle 사용은 각각의 데이터 유형에 따라 다르니, 상황에 맞춰서 사용하면 된다.


 * 주의 : 데이터를 참조하기 전에 데이터 읽어 오기가 끝났는지 확인 하자. 아래는 그 방법 중 하나다.

if ( www != null && www.isDone )
{
    // 데이터 참조 시작!
}
반응형