using System.Collections;
using System.Collections.Generic;
using UnityEngine; /// <summary>
/// LoadAssets打开某资源文件并加载其中的所有Prefab到场景中
/// </summary>
public class LoadAssets : MonoBehaviour
{
[HideInInspector]
public string address;//资源所在文件夹路径
public string fileToLoad;//资源文件名
private string manifestAssetBundleName;//Manifest文件,一般与所在文件夹名称相同
private AssetBundleManifest manifest;
private List<AssetBundle> assetBundles = new List<AssetBundle>(); private void Awake()
{
if(address.Equals(""))
return;
//Manifest文件的名称与生成的AssetBundle所在的文件夹同名
string[] ss = address.Split('/');
manifestAssetBundleName = ss[ss.Length - ];
LoadManifest(address + manifestAssetBundleName);
LoadDepend(fileToLoad); }
void OnGUI()
{
if (address.Equals(""))
return;
//第1步:读取Manifest
if (GUILayout.Button("地图加载(选择map.unity3d)"))
{
StartCoroutine(LoadObj(address, fileToLoad));
Caching.CleanCache();
}
}
//同步下载并读取Manifest文件
public void LoadManifest(string mainfestpath)
{
//Debug.Log("LoadManifest:"+mainfestpath);
AssetBundle manifestBundle = AssetBundle.LoadFromFile(mainfestpath);
if (manifestBundle != null)
{
manifest = (AssetBundleManifest)manifestBundle.LoadAsset("AssetBundleManifest");
}
}
//获取资源所依赖的资源并下载
void LoadDepend(string assetName)
{
string[] dps = manifest.GetAllDependencies(assetName);
for (int i = ; i < dps.Length; i++)
{
StartCoroutine(LoadAsset(address, dps[i]));
}
}
//下载资源
IEnumerator LoadAsset(string url, string fileName)
{
//Debug.Log("LoadAsset:" + url+" "+fileName);
WWW www = WWW.LoadFromCacheOrDownload("file://" + url + fileName, manifest.GetAssetBundleHash(fileName));
yield return www;
assetBundles.Add(www.assetBundle);
www.Dispose();
}
//下载并实例化游戏对象
IEnumerator LoadObj(string url, string fileName)
{
//Debug.Log("LoadOBJ:" + url + " " + fileName); WWW www = WWW.LoadFromCacheOrDownload("file://" + url + fileName, manifest.GetAssetBundleHash(fileName));
yield return www;
string[] AssetsNames = www.assetBundle.GetAllAssetNames();
foreach (string m in AssetsNames)
{
GameObject prefab = www.assetBundle.LoadAsset(m) as GameObject;
GameObject obj = GameObject.Instantiate(prefab);
} assetBundles.Add(www.assetBundle);
www.Dispose();
UnloadUnuseAssetBundle();
}
//清理未使用资源所占用的内存
void UnloadUnuseAssetBundle()
{
foreach (var item in assetBundles)
{
item.Unload(false);
}
}
}
05-02 19:35