Unity AssetBundle 載入

城平八發表於2019-02-26

1.根據打包的manifes檔案載入所有assetbundle包

C# 
// 下載所有assetbundle包
Ienumerator DownLoadMainAssetBundle()
{
   UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(mainAssetBundleURL);
    yield return request.SendWebRequest();
    AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(request);
      AssetBundleManifest manifest = assetBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
    string[] names = manifest.GetAllAssetBundles();
    for(int i=0;i<names.Length;i++)
    {
        StartCoroutine(DownLoadAssetBundleAndSave(allAssetBundleURL+name[i]));
    }
}

   IEnumerator DownLoadAssetBundleAndSave(string url)
{
    WWW www = new WWW(url);
    yield return www;
    if(www.isDone)
    {
        SaveAssetBundle(Path.GetFileName(url),www.bytes,www.bytes.Length);
    }
}

private void SaveAssetBundle(string fileName,byte[] bytes,int count)
{
    FileInfo fileInfo = new FileInfo(Application.streamingAssetsPath+"//"+fileName);
    FileStream fs = fileInfo.Create();
    fs.Write(bytes,0,count);
    fs.Flush();
    fs.Close();
    fs.Dispose();
    Debug.Log("下載完畢");
}

IEnumerator DownLoadSingleAssetBundle(string url)
{
    UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url);
    yield return request.SendWebRequest();
    AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(request);
    string[] names = assetBundle.GetAllAssetNames();
    for(int i=0;i<names.Length;i++)
    {
        string tempName = Path.GetFileNameWithoutExtension(names[i]);
        GameObject obj = assetBundle.LoadAsset<GameObject>(tempName);
        Instantiate(obj);
    }
}

相關文章