資源管理導(dǎo)圖
準(zhǔn)備工作
- 設(shè)置Asset Labels(Unity右下角)
- Cube ------ cubeprefab
- mat ------- cubemat
- pic ------- cubetexture
待會加載資源就是靠標(biāo)簽加載的
一鍵打包的實現(xiàn)
using UnityEngine;
using UnityEditor;
using System.IO;
public class BuildAssetBundle : Editor
{
[MenuItem("AssetBundle/Build/Windows")]
public static void BuildWindows()
{
//AssetBundle的存儲路徑
string path = Application.dataPath + "/AssetBundle/Windows/";
//如果路徑不存在
if (!File.Exists(path))
{
//創(chuàng)建路徑
Directory.CreateDirectory(path);
}
//打包
BuildPipeline.BuildAssetBundles(path, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
//打印
Debug.Log("打包成功");
}
}
打包完成后刪掉"CubeAsset"文件夾(其實刪不刪無所謂誓琼,主要是確認(rèn)資源是從AssetBundle里面加載出來的)
AssetBundle文件夾的信息
加載紋理圖(無依賴關(guān)系)
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class LoadTexture : MonoBehaviour
{
private string path;
public string bundleName;
public string assetName;
private void Awake()
{
path = "file://" +Application.dataPath + "/AssetBundle/Windows/";
}
private IEnumerator Start()
{
WWW www = new WWW(path + bundleName);
//下載
yield return www;
//獲取AssetBundle
AssetBundle ab = www.assetBundle;
//加載資源
Texture t = ab.LoadAsset(assetName) as Texture;
//放圖片
GetComponent<RawImage>().texture = t;
//釋放資源
ab.Unload(false);
}
}
bundleName和assetNam根據(jù)一鍵打包的結(jié)果名稱和原圖片資源名稱決定
加載預(yù)設(shè)體(有依賴關(guān)系)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LoadCube : MonoBehaviour
{
private string path;
/// <summary>
/// 資源的Bundle名稱
/// </summary>
public string bundleName;
/// <summary>
/// 資源本身的名稱
/// </summary>
public string assetName;
/// <summary>
/// 版本號
/// </summary>
public int version = 0;
private void Awake()
{
path = "file://" + Application.dataPath + "/AssetBundle/Windows/";
}
private IEnumerator Start()
{
//下載整個資源管理系統(tǒng)的說明文件
WWW www = WWW.LoadFromCacheOrDownload(path+"Windows",version);
//下載
yield return www;
//獲取到說明文件的Bundle
AssetBundle mani = www.assetBundle;
//加載Mani文件
AssetBundleManifest manifest = mani.LoadAsset("AssetBundleManifest") as AssetBundleManifest;
//查當(dāng)前要加載的資源的所有依賴
string[] deps = manifest.GetAllDependencies(bundleName);
//釋放ManiBundle
mani.Unload(false);
//聲明依賴的Bundle數(shù)組
AssetBundle[] depBundles = new AssetBundle[deps.Length];
//依次下載依賴
for (int i = 0; i < depBundles.Length; i++)
{
//下載依賴
www = WWW.LoadFromCacheOrDownload(path + deps[i], version);
//等待下載
yield return www;
//獲取Bundle
depBundles[i] = www.assetBundle;
}
//下載最終的資源bundle
www = WWW.LoadFromCacheOrDownload(path + bundleName, version);
//等待
yield return www;
//獲取Bundle
AssetBundle realBundle = www.assetBundle;
//獲取資源
GameObject prefab = realBundle.LoadAsset(assetName) as GameObject;
//生成對象
Instantiate(prefab);
//釋放Bundle
realBundle.Unload(false);
for (int i = 0; i < deps.Length; i++)
{
depBundles[i].Unload(false);
}
}
}