(Unity) DataModule - AssetBundle

고현서·2022년 12월 8일
1

DataModule

목록 보기
3/3

마지막! AssetBundle을 다운로드 받아보도록 하겠습니다!

이번에 사용한 AssetBundle의 용도를 설명해드리도록 하겠습니다!

사용자가 커스텀한 오브젝트를 Web Application Server에 올리면, 나중에 후에 구매자가 Web에서 커스텀한 오브젝트를 다운로드 받을 때, AssetBundle 형태로 다운로드 받습니다!

이번에도 저번에 설명드린 중복 부분은 생략하고,
AssetBundle에서 따로 다뤄야할 부분을 살펴보겠습니다!

1. Request 생성

Assetbundle을 Get만 하기 때문에 Get만 고려하였습니다.
해당 requestURL에서 Get하여 request를 생성해줍니다!

       //웹 요청 생성(Get,Post,Delete,Update)
        UnityWebRequest request = UnityWebRequest.Get(requestURL);

2. AssetBundle 다운로드 및 로컬 저장

AssetBundle을 Byte 배열 형식으로 data를 downloadHandler에서 가져온 후 파일을 특정 경로에 씁니다.

그렇게 된다면 AssetBundle이 파일형태로 로컬에 저장됩니다.

			var res = await request.SendWebRequest().WithCancellation(cts.Token);

#if UNITY_STANDALONE
            //번들을 자동적으로 로컬에 저장한다.
            string assetBundleDirectory = Application.dataPath + "/MarketBundle";
#elif UNITY_IOS
            string assetBundleDirectory = Application.persistentDataPath + "/MarketBundle";
#endif
            if (!Directory.Exists(assetBundleDirectory + "/" + bundleName.Split("/")[0]))
            {
                Directory.CreateDirectory(assetBundleDirectory + "/" + bundleName.Split("/")[0]);
            }

            FileStream fs = new FileStream(assetBundleDirectory + "/" + bundleName, FileMode.Create);
            fs.Write(request.downloadHandler.data, 0, (int)request.downloadedBytes);
            fs.Close();
            request.Dispose();

최종 코드

	/// <summary>
    /// AssetBundle 받는 코드
    /// </summary>
    /// <param name="_url"></param>
    /// <param name="networkType"></param>
    /// <param name="dataType"></param>
    /// <param name="data"></param>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public static async UniTask<AssetBundle> WebRequestAssetBundle(string _url, NetworkType networkType, DataType dataType, string bundleName, string filePath = null)
    {
        //네트워크 체킹
        await CheckNetwork();
        //API URL 생성
        string requestURL = DOMAIN + _url;
        //Timeout 설정
        var cts = new CancellationTokenSource();
        cts.CancelAfterSlim(TimeSpan.FromSeconds(timeout));

        //웹 요청 생성(Get,Post,Delete,Update)
        UnityWebRequest request = UnityWebRequest.Get(requestURL);

        //Header 정보 입력
        if (REPLACE_BEARER_TOKEN == "" && PlayerPrefs.GetString("Bearer") != "")
        {
            REPLACE_BEARER_TOKEN = PlayerPrefs.GetString("Bearer");
        }

        SetHeaders(request, "Authorization", "Bearer " + REPLACE_BEARER_TOKEN);
        SetHeaders(request, "Content-Type", "application/json");

        try
        {
            var res = await request.SendWebRequest().WithCancellation(cts.Token);

#if UNITY_STANDALONE
            //번들을 자동적으로 로컬에 저장한다.
            string assetBundleDirectory = Application.dataPath + "/MarketBundle";
#elif UNITY_IOS
            string assetBundleDirectory = Application.persistentDataPath + "/MarketBundle";
#endif
            if (!Directory.Exists(assetBundleDirectory + "/" + bundleName.Split("/")[0]))
            {
                Directory.CreateDirectory(assetBundleDirectory + "/" + bundleName.Split("/")[0]);
            }

            FileStream fs = new FileStream(assetBundleDirectory + "/" + bundleName, FileMode.Create);
            fs.Write(request.downloadHandler.data, 0, (int)request.downloadedBytes);
            fs.Close();
            request.Dispose();

            //리턴은 하지 않는다. 
            return default;
        }
        catch (OperationCanceledException ex)
        {
            if (ex.CancellationToken == cts.Token)
            {
                Debug.Log("Timeout");
                //TODO: 네트워크 재시도 팝업 호출.

                //재시도
                return await WebRequestAssetBundle(_url, networkType, dataType, bundleName);
            }
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
            request.Dispose();
            return default;
        }
        request.Dispose();
        return default;
    }
profile
New 현또의 코딩세상 / Unity 개발자

0개의 댓글