1. 程式人生 > >Unity AssetBundle -- 載入本地AssetBundle

Unity AssetBundle -- 載入本地AssetBundle

關於Unity AssetBundle – 載入本地AssetBundle
一、前提知識:
1、匯出的AssetBundle主要包含兩類檔案:各類資源的assetbundle檔案和對應的manifest檔案
2、assetbundle檔案是需要下載或者載入的檔案,manifest檔案是用於展示的各項資源的依賴關係檔案
3、載入資源時需要的依賴關係檔案包含在不帶字尾名的、由使用者自定義的assetbundle檔案。manifest檔案只是用於本地的增量打包

二、載入本地AssetBundle
//檢測平臺
#if UNITY_STANDALONE_WIN
string localPath = “LOCAL_PATH

”;
string wwwPath = “WEB_PATH”;
#endif

可以使用協程

    void Start () {
            ...
            StartCoroutine(DownloadAssetBundle());
    }

    IEnumerator LoadAssetBundleFromFile()
    {
		...
    }

在協程中可以進行資源的載入
首先需要載入沒有後綴名的那個由使用者定義名稱的assetbundle檔案,它儲存了所有資源依賴關係
載入的assetbundle檔案中包含一個名為"assetbundlemanifest"的AssetBundleManifest 型別檔案,利用LoadAsset載入

	string manifestName = "assetbundlemanifest";
	AssetBundle assetBundle = AssetBundle.LoadFromFile(localPath + assetBundleName);
	AssetBundleManifest manifest = assetBundle.LoadAsset<AssetBundleManifest>(manifestName);

通過得到的manifest檔案,獲取各類資源的依賴關係

	string[] dps = manifest.GetAllDependencies(assetName);

根據所得的依賴關係載入其它相關資源,載入的assetbundle資源中包含了所需的Asset資源

	for (int i = 0; i < nameArray.Length; i++)
	{
		assetBundleList.Add(AssetBundle.LoadFromFile(localPath + nameArray[i]));
	}

載入你的目標assetbundle

	goalBundle = AssetBundle.LoadFromFile(path);

目前載入assetbundle獲取的資源在記憶體中以映象包的形式存在,需要使用LoadAsset獲取到真正可用的資源,並例項化

	GameObject redSphere = goalBundle.LoadAsset<GameObject>("Assets/Prefabs/Sphere.prefab");
	Instantiate(redSphere);

資源中並沒有相關紅色球體的assets

利用之前載入的assetbundle中的assets生成一個紅色的球體