using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ABMgr : SingletonMono<ABMgr>
{
//AB包管理器 目的是
//让外部更方便的进行资源加载
//特点:AB包不能重复加载,重复加载会报错。
private Dictionary<string, AssetBundle> abDic = new Dictionary<string, AssetBundle>();
//主包
private AssetBundle mainAB = null;
//配置文件
private AssetBundleManifest manifest = null;
/// <summary>
/// AB包存放路径 方便修改
/// </summary>
private string pathUrl
{
get
{
return Application.streamingAssetsPath + "/";
}
}
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);
}
}
//如果没有这个包名就加载
if (!abDic.ContainsKey(abName))
{
ab = AssetBundle.LoadFromFile(pathUrl + abName);
abDic.Add(abName, ab);
}
}
//同步加载
public Object LoadRes(string abName, string resName)
{
LoadAB(abName);
//加载资源
Object obj = abDic[abName].LoadAsset(resName);
if (obj is GameObject)
{
return Instantiate(obj);
}
else
{
return obj;
}
}
//根据类型指定
public Object LoadRes(string abName, string resName,System.Type type)
{
LoadAB(abName);
//加载资源
Object obj = abDic[abName].LoadAsset(resName,type);
if (obj is GameObject)
{
return Instantiate(obj);
}
else
{
return obj;
}
}
//根据泛型指定
public Object LoadRes<T>(string abName, string resName)where T:Object
{
LoadAB(abName);
//加载资源
T obj = abDic[abName].LoadAsset<T>(resName);
if (obj is GameObject)
{
return Instantiate(obj);
}
else
{
return obj;
}
}
//卸载单个包
public void UnLoad(string abName)
{
if (abDic.ContainsKey(abName))
{
abDic[abName].Unload(false);
abDic.Remove(abName);
}
}
//卸载所有包
public void ClearAB()
{
AssetBundle.UnloadAllAssetBundles(false);//卸载所有AB包
abDic.Clear();
}
}