一、AssetBundle生成打包

设置将要打包的资源的AssetBundle


第一个新建或选择一个名称,例如aa、aa/bb
第二个新建或选择一个后缀,一般使用ab、assetbundle、unity3d

AssetBundle打包前在Assets下创建文件夹‘StreamingAssets’
AssetBundle打包方法:AssetBundleManifest BuildAssetBundles(string outputPath, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform);
参数1:保存路径
参数2:压缩方式
参数3:选择平台
新建一个脚本放置在Editor文件中,Editor中的文件不会打包出来
//新建一个脚本,添加代码如下:
[MenuItem ("Build/BuildAssetBundle")]
    static void BuildAssetBudle()
    {
#if UNITY_ANDROID
        BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath, BuildAssetBundleOptions.None, BuildTarget.Android);
        Debug.Log("Android打包AssetBundle");
#elif UNITY_EDITOR
        BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
        Debug.Log("Windows打包AssetBundle");
#endif
    }

二、下载保存本地

	string uri;
    string localAssetPath;

    void Start()
    {
    	//服务器保存资源地址
        uri = "http://***/***/***/资源名字.资源后缀";
        //本地保存位置
        //Android:Application.persistentDataPath PC:Application.streamingAssetsPath
        localAssetPath = Application.persistentDataPath + "/资源名字.资源后缀";
        StartCoroutine(DownLoadAsset());
    }
    
    //使用协程 加载网址下载资源
	IEnumerator DownLoadAsset()
    {
        string directoryPath = Path.GetDirectoryName(localAssetPath);
        if (!Directory.Exists(directoryPath))
        {
            Debug.Log("创建路径:" + directoryPath);
            Directory.CreateDirectory(directoryPath);
            Debug.Log("创建路径成功");
            txt.text = "创建路径成功";
        }
        
        while (Application.internetReachability == NetworkReachability.NotReachable)
        {
            Debug.Log("未连接网络");
            yield return 0;
        }
        
        //获取资源文件总大小
        //using (UnityWebRequest headRequest = UnityWebRequest.Head(url))
        //{
        //    yield return headRequest.SendWebRequest();
        //    ulong totalLength = ulong.Parse(headRequest.GetResponseHeader("Content-Length"));//获取文件总大小
        //    txt.text = totalLength.ToString();
        //    headRequest.Dispose();
        //}
        
        using (UnityWebRequest webRequest = UnityWebRequestAssetBundle.GetAssetBundle(uri))
        {
            DownloadHandlerFile downloadHandler = new DownloadHandlerFile(localAssetPath);
            downloadHandler.removeFileOnAbort = true;
            webRequest.downloadHandler = downloadHandler;
            webRequest.SendWebRequest();
            
            while (!webRequest.isDone)
            {
                if (GameObject.FindObjectOfType<LevelPanel>() != null)
                {
                    LevelPanel.instance.downLoadProgressTxt.text = "资源下载中 " + Math.Floor(webRequest.downloadProgress * 100) + "%";
                }
                Debug.Log("进度: " + webRequest.downloadProgress.ToString());
                yield return 0;
            }
            
            if (!string.IsNullOrEmpty(webRequest.error))
            {
                Debug.Log("下载错误");
                while (Application.internetReachability == NetworkReachability.NotReachable)
                {
                	Debug.Log("下载错误!请链接网络,重新下载");
                    yield return 0;
                }
                StartCoroutine(DownLoadAssets());
                //using (UnityWebRequest webRequest1 = UnityWebRequestAssetBundle.GetAssetBundle(url))
                //{
                //    DownloadHandlerFile downloadHandler1 = new DownloadHandlerFile(localAssetPath, true);
                //    //downloadHandler1.removeFileOnAbort = true;
                //    webRequest1.downloadHandler = downloadHandler1;
                //    FileInfo file = new FileInfo(localAssetPath);
                //    ulong fileLength = (ulong)file.Length;
                //    txt.text += " -- " + fileLength + "+";
                //    txt.text = Application.persistentDataPath;
                //    webRequest1.SetRequestHeader("Range", "bytes=" + fileLength + "-");
                //    webRequest1.SendWebRequest();
                //    while (!webRequest.isDone)
                //    {
                //        loadTxt.text = "资源下载 " + Math.Floor(webRequest1.downloadProgress * 100) + "%";
                //        loadImg.fillAmount = webRequest1.downloadProgress;
                //        Debug.Log("进度: " + webRequest1.downloadProgress.ToString());
                //        yield return 0;
                //    }
                //    if (webRequest1.isDone)
                //    {
                //        txt.text += webRequest1.downloadedBytes.ToString();
                //        PlayerPrefs.SetInt("DownLoadAsset", 1);
                //        LoadScene();
                //        Debug.Log("完成: " + localAssetPath);
                //        yield return null;
                //    }
                //}
            }
            else
            {
                if (webRequest.isDone)
                {
                    Debug.Log("下载完成: " + localAssetPath);
                    yield return null;
                }
            }
            //完成不再使用
            webRequest.Dispose();
        }

三、读取

AssetBundle ab = AssetBundle.LoadFromFile(Application.persistentDataPath + "/level.assetbundle");
GameObject g = ab.LoadAsset<GameObject>(currentLevel.ToString());
Instantiate(g);
ab.Unload(false);
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐