Unity3D资源异步加载(二)——AssetBundle资源打包、加载

2021-02-15 13:22

阅读:356

标签:ble   source   获取   lse   打包   zip   mat   work   audio   

AssetBundle就像一个ZIP压缩文件,里面存储着不同平台的特殊资源(models/texture/prefabs/materials/audio clip/scenes...), 这些资源都可以在运行时进行加载。
上一章介绍了,资源异步加载的方法,这篇介绍AssetBundle资源旧的打包加载方法;
AssetBundle打包:
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;

public class AssetbundlePack : MonoBehaviour {

    /// 
    /// 查看所有的Assetbundle名称
    /// 
    [MenuItem("AssetBundle/Get AssetBundle names")]
    static void GetAllAssetbundleNames()
    {
        var names = AssetDatabase.GetAllAssetBundleNames(); //获取所有设置的AssetBundle
        foreach (var name in names)
            Debug.Log("AssetBundle: " + name);
    }

    /// 
    /// 自动打包所有资源
    /// 
    [MenuItem("AssetBundle/Create AssetBundles")] //设置编辑器菜单选项
    static void CreateAllAssetBundles()
    {
        string targetPath = Application.dataPath + "/StreamingAssets/PCAssetsResources/";
        if(!Directory.Exists(targetPath))
        {
            Directory.CreateDirectory(targetPath);
        }
        //打包资源
                ////参数一为打包到哪个路径,参数二压缩选项  参数三 平台的目标
        BuildPipeline.BuildAssetBundles(targetPath, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
        //刷新编辑器
        AssetDatabase.Refresh();
    }

    /// 
    /// 清除之前设置过的AssetBundleName,避免产生不必要的资源也打包 
    /// 因为只要设置了AssetBundleName的,都会进行打包,不论在什么目录下 
    ///  
    [MenuItem("AssetBundle/Clear All Assetbundle Name")]
    public static void ClearAssetBundlesName()
    {
        string[] oldAssetBundleNames = AssetDatabase.GetAllAssetBundleNames();
        for (int j = 0; j 

异步加载AssetBundle

  /// 
    /// 请求AssetBundle
    /// 
    /// AssetBundle地址
    /// 请求发起后处理回调结果的委托,处理请求结果的AssetBundle
    /// 
    IEnumerator _LoadAssetBundle(string url, Action actionResult)
    {
         using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            DownloadHandlerAssetBundle downloadAssetBundle = new DownloadHandlerAssetBundle(url, uint.MaxValue);
            request.downloadHandler = downloadAssetBundle;
            yield return request.SendWebRequest();
            AssetBundle assetBundle = null;
            string text = null;
            if (!(request.isNetworkError || request.isHttpError))
            {
                assetBundle = downloadAssetBundle.assetBundle;
            }
            else
            {
                text = request.error;
            }
            if (actionResult != null)
            {
                actionResult.Invoke((request.isNetworkError || request.isHttpError), text, assetBundle);
            }
        }
    }

AssetBundle旧方法打包加载就介绍到这里,自2018版Unity发布之后出现新的资源管理方式Addressable,不过旧的依然能用,个人觉得新Addressable方式用起来方便的多,Addressable也是基于AssetBundle之上,下一篇主要介绍Addressable使用。

Unity3D资源异步加载(二)——AssetBundle资源打包、加载

标签:ble   source   获取   lse   打包   zip   mat   work   audio   

原文地址:https://blog.51cto.com/myselfdream/2487873


评论


亲,登录后才可以留言!