管理类中继承的单例框架见上篇https://blog.csdn.net/YuKar_/article/details/133135713?spm=1001.2014.3001.5501
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ABManager : Singleton<ABManager>
{
//主包
private AssetBundle ab_main = null;
//获取依赖包所需的配置文件
private AssetBundleManifest manifest = null;
//记录ab包的字典
private Dictionary<string, AssetBundle> abDir = new Dictionary<string, AssetBundle>();
//AB包默认路径
private string pathURL
{
get
{
//资源路径
return @"D:\Unity Projects\ABManager\AssetBundles\PC\";
}
}
//AB包目录名字
private string abDefaultName
{
get
{
return "PC";
}
}
//获取ab包资源
private void LoadAB(string abName)
{
if (ab_main == null)
{
//加载主包
ab_main = AssetBundle.LoadFromFile(pathURL + abDefaultName);
manifest = ab_main.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
//获取依赖包相关信息
AssetBundle ab;
string[] str = manifest.GetAllDependencies(abName);
for (int i = 0; i < str.Length; i++)
{
if (!abDir.ContainsKey(str[i]))
{
ab = AssetBundle.LoadFromFile(pathURL + str[i]);
abDir.Add(str[i],ab);
}
}
//加载资源来源包
if (!abDir.ContainsKey(abName))
{
ab = AssetBundle.LoadFromFile(pathURL + abName);
abDir.Add(abName, ab);
}
}
}
//同步加载
public Object LoadRes(string abName,string resName)
{
LoadAB(abName);
return abDir[abName].LoadAsset(resName);
}
//同步加载(指定类型)
public Object LoadRes(string abName,string resName ,System.Type type)
{
LoadAB(abName);
return abDir[abName].LoadAsset(resName , type);
}
//异步加载
public void LoadResAsync(string abName,string resName)
{
StartCoroutine(ReallyLoadResAsync(abName, resName));
}
private IEnumerator ReallyLoadResAsync(string abName,string resName)
{
LoadAB(abName);
AssetBundleRequest abr = abDir[abName].LoadAssetAsync(resName);
yield return abr;
if(abr.asset != null)
{
Debug.Log("加载成功");
Instantiate(abr.asset);
}
else
{
Debug.LogWarning("资源加载失败");
}
}
//单个包卸载
public void UnLoad(string abName)
{
if (abDir.ContainsKey(abName))
{
abDir[abName].Unload(false);
abDir.Remove(abName);
}
}
//全部包卸载
public void ClearAB()
{
AssetBundle.UnloadAllAssetBundles(false);
abDir.Clear();
ab_main = null;
manifest = null;
}
}
测试代码
其中第一个参数为AB包名字,第二个参数为AB包中对应的资源名字,这里获取并实例化"model"包中的"cube"物体。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ABTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//同步加载
Object obj = ABManager.Instance.LoadRes("model", "cube");
Instantiate(obj);
//同步加载(指定类型)
//obj = ABManager.Instance.LoadRes("model", "cube", typeof(GameObject));
//Instantiate(obj);
//异步加载
//ABManager.Instance.LoadResAsync("model", "cube");
}
}
执行对应方法后即可生成对应资源文件。