AB包

这篇博客介绍了在 Unity 中如何进行 AssetBundle 的同步和异步加载,包括依赖处理、资源管理器的实现以及协程的使用。展示了如何在不同场景下加载和卸载 AssetBundle,同时提供了资源管理类 `ABMgr` 的详细代码,该类支持泛型和委托,方便资源的加载和释放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AB包加载

同步

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ABtest : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //加载AB包
        AssetBundle ab = AssetBundle.LoadFromFile(Application.streamingAssetsPath + "/" + "model");
        //加载AB包中的资源,不推荐泛型,LUA不能用
        //GameObject obj = ab.LoadAsset<GameObject>("cube");
        GameObject obj = ab.LoadAsset("cube", typeof(GameObject)) as GameObject;
        Instantiate(obj);

 		//true会连同场景中已加载的资源一起卸载
        ab.Unload(false);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

异步——协程

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ABtest2 : MonoBehaviour
{
    public Image img;
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(LoadAB("model", "cube"));
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    IEnumerator LoadAB(string abName,string resName)
    {
        AssetBundleCreateRequest abcr = AssetBundle.LoadFromFileAsync(Application.streamingAssetsPath + "/" + abName);
        yield return abcr;
        AssetBundleRequest abr = abcr.assetBundle.LoadAssetAsync(resName,typeof(GameObject));
        yield return abr;
        GameObject obj = abr.asset as GameObject;
        Instantiate(obj);
        
    }
}

依赖

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ABtest : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //加载AB包
        AssetBundle ab = AssetBundle.LoadFromFile(Application.streamingAssetsPath + "/" + "model");



        //加载主包
        AssetBundle abMain = AssetBundle.LoadFromFile(Application.streamingAssetsPath + "/" + "PC");
        //加载主包中的固定文件
        AssetBundleManifest abMainifest = abMain.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
        //从固定文件中得到依赖信息
        string[] strs = abMainifest.GetAllDependencies("model");
        //得到依赖包的名字
        for (int i = 0; i < strs.Length; i++)
        {
            AssetBundle.LoadFromFile(Application.streamingAssetsPath + "/" + strs[i]);
        }



        //加载AB包中的资源,不推荐泛型,LUA不能用
        //GameObject obj = ab.LoadAsset<GameObject>("cube");
        GameObject obj = ab.LoadAsset("cube", typeof(GameObject)) as GameObject;
        Instantiate(obj);
        //true会连同场景中已加载的资源一起卸载
        //ab.Unload(false);





    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

AB包资源管理器

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

/// <summary>
/// 涉及知识点
/// 1.AB包相关API
/// 2.单例
/// 3.委托——>Lambda表达式
/// 4.协程
/// 5.字典
/// </summary>
public class ABMgr : SingletonAutoMono<ABMgr>
{
    //主包
    private AssetBundle mainAB = null;
    //主包的固定文件
    private AssetBundleManifest manifest = null;     

    //容器,存储加载过的AB包
    private Dictionary<string, AssetBundle> abDic = new Dictionary<string, AssetBundle>();

    /// <summary>
    /// AB包存放路径,方便修改
    /// </summary>
    private string PathUrl
    {
        get
        {
            return Application.streamingAssetsPath + "/";
        }
    }
    /// <summary>
    /// 主包名,方便修改
    /// </summary>
    private string MainABName
    {
        get
        {
#if UNITY_IOS
            return "IOS";
# elif UNITY_ANDROID
            return "Android";
#else
            return "PC";
#endif
        }
    }


    private void LoadAB(string abName)
    {
        if (mainAB == null)
        {
            //主包
            mainAB = AssetBundle.LoadFromFile(PathUrl + MainABName);
            //主包固定文件
            manifest = mainAB.LoadAsset<AssetBundleManifest>("AssetBundleManifest");

        }
        //当临时变量用
        AssetBundle ab;
        //依赖信息
        string[] strs = manifest.GetAllDependencies(abName);
        for (int i = 0; i < strs.Length; i++)
        {
            //判断包是否被加载过
            if (!abDic.ContainsKey(strs[i]))
            {
                ab = AssetBundle.LoadFromFile(PathUrl + strs[i]);
                abDic.Add(strs[i], ab);
            }
        }

        //加载要用的AB包      
        if (!abDic.ContainsKey(abName))
        {
            ab = AssetBundle.LoadFromFile(PathUrl + abName);
            abDic.Add(abName, ab);
        }

    }

    //同步加载,LUA不支持泛型,用重载
    /// <summary>
    /// 不指定类型
    /// </summary>
    /// <param name="abName"></param>
    /// <param name="resName"></param>
    /// <returns></returns>
    public Object LoadRes(string abName, string resName)
    {
        LoadAB(abName);

        //判断一下是不是GameObject,省的在外面再实例化
        Object obj = abDic[abName].LoadAsset(resName);
        if (obj is GameObject)
            return Instantiate(obj);
        else
            return obj;

      


    }
    /// <summary>
    /// 指定类型
    /// </summary>
    /// <param name="abName"></param>
    /// <param name="resName"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public Object LoadRes(string abName, string resName, System.Type type)
    {
        LoadAB(abName);

        //判断一下是不是GameObject,省的在外面再实例化
        Object obj = abDic[abName].LoadAsset(resName,type);
        if (obj is GameObject)
            return Instantiate(obj);
        else
            return obj;
    }
    /// <summary>
    /// 根据泛型指定类型
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="abName"></param>
    /// <param name="resName"></param>
    /// <returns></returns>
    public T LoadRes<T>(string abName, string resName) where T:Object
    {
        LoadAB(abName);

        //判断一下是不是GameObject,省的在外面再实例化
        T obj = abDic[abName].LoadAsset<T>(resName);
        if (obj is GameObject)
            return Instantiate(obj);
        else
            return obj;
    }

    //异步加载
    //这里的异步加载,AB包并没有使用异步,只是从AB包中加载资源时使用异步
    /// <summary>
    /// 根据名字异步加载资源
    /// </summary>
    /// <param name="abName"></param>
    /// <param name="resName"></param>
    /// <param name="callBack"></param>
    public void LoadResAsync(string abName,string resName,UnityAction<Object> callBack)
    {
        StartCoroutine(ReallyLoadResAsync(abName, resName, callBack));
    }
    private IEnumerator ReallyLoadResAsync(string abName, string resName, UnityAction<Object> callBack)
    {
        LoadAB(abName);

        //判断一下是不是GameObject,省的在外面再实例化
        AssetBundleRequest abr = abDic[abName].LoadAssetAsync(resName);
        yield return abr;
        //异步加载结束后,通过委托传递给外部,外部来使用
        if (abr.asset is GameObject)
            callBack(Instantiate(abr.asset));
        else
            callBack(abr.asset);

    }

    /// <summary>
    /// 根据type异步加载资源
    /// </summary>
    /// <param name="abName"></param>
    /// <param name="resName"></param>
    /// <param name="callBack"></param>
    public void LoadResAsync(string abName, string resName,System.Type type, UnityAction<Object> callBack)
    {
        StartCoroutine(ReallyLoadResAsync(abName, resName, type,callBack));
    }
    private IEnumerator ReallyLoadResAsync(string abName, string resName, System.Type type,UnityAction<Object> callBack)
    {
        LoadAB(abName);

        //判断一下是不是GameObject,省的在外面再实例化
        AssetBundleRequest abr = abDic[abName].LoadAssetAsync(resName,type);
        yield return abr;
        //异步加载结束后,通过委托传递给外部,外部来使用
        if (abr.asset is GameObject)
            callBack(Instantiate(abr.asset));
        else
            callBack(abr.asset);

    }

    /// <summary>
    /// 根据泛型异步加载资源
    /// </summary>
    /// <param name="abName"></param>
    /// <param name="resName"></param>
    /// <param name="type"></param>
    /// <param name="callBack"></param>
    public void LoadResAsync<T>(string abName, string resName, UnityAction<T> callBack) where T:Object
    {
        StartCoroutine(ReallyLoadResAsync<T>(abName, resName,  callBack));
    }
    private IEnumerator ReallyLoadResAsync<T>(string abName, string resName,  UnityAction<T> callBack) where T : Object
    {
        LoadAB(abName);

        //判断一下是不是GameObject,省的在外面再实例化
        AssetBundleRequest abr = abDic[abName].LoadAssetAsync<T>(resName);
        yield return abr;
        //异步加载结束后,通过委托传递给外部,外部来使用
        if (abr.asset is GameObject)
            callBack(Instantiate(abr.asset) as T);
        else
            callBack(abr.asset as T);

    }
    //单个包卸载
    public void UnLoad(string abName)
    {
        if (abDic.ContainsKey(abName))
        {
            abDic[abName].Unload(false);
            abDic.Remove(abName);
        }
    }

    //所有包卸载
    public void ClearAB()
    {
        AssetBundle.UnloadAllAssetBundles(false);
        abDic.Clear();
        mainAB = null;
        manifest = null;
    }
    
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ABMgrTest : MonoBehaviour
{

    void Start()
    {
        //测试1

        /*   GameObject obj = ABMgr.GetInstance().LoadRes("model", "Cube", typeof(GameObject)) as GameObject;
           obj.transform.position = -Vector3.up;

           GameObject obj2 = ABMgr.GetInstance().LoadRes<GameObject>("model", "Cube");
           obj2.transform.position = Vector3.up;*/


        //测试2
        ABMgr.GetInstance().LoadResAsync<GameObject>("model", "Cube", (obj) =>
          {
              (obj as GameObject).transform.position = -Vector3.up;
          });
    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值