Unity 4.x 资源加载

时间:2023-03-09 06:38:50
Unity 4.x 资源加载
using UnityEngine;
using System.Collections;
using System.IO; public class LoadResource : MonoBehaviour
{
//assetbundle 的后缀实际上可以随意自定义的
string PathAssetBundle = "D:/LgsTest/ResourcePath/Cube.assetbundle";
void Start()
{
//StartCoroutine(LoadFromMemoryAsync());
//LoadFromMemorySync();
//LoadFromLocalFile();
StartCoroutine(LoadFromWWW());
} #region 第一种加载AB的方式,从内存中加载 //通过Bundle的二进制数据,异步创建AssetBundle对象。完成后会在内存中创建较大的WebStream。
//调用时,Bundle的解压是异步进行的,因此对于未压缩的Bundle文件,该接口与CreateFromMemoryImmediate等价。
IEnumerator LoadFromMemoryAsync()
{
AssetBundleCreateRequest request = AssetBundle.CreateFromMemory(File.ReadAllBytes(PathAssetBundle));
yield return request;
AssetBundle bundle = request.assetBundle;
Instantiate(bundle.Load("Cube"));
} void LoadFromMemorySync()
{
AssetBundle bundle = AssetBundle.CreateFromMemoryImmediate(File.ReadAllBytes(PathAssetBundle));
Instantiate(bundle.Load("Cube"));
}
#endregion #region 第二种加载AB的方式,从本地中加载 //加载的资源只能是未压缩的(即在打包资源的时候要加上 BuildAssetBundleOptions.UncompressedAssetBundle),压缩过的资源会加载失败
//通过未压缩的Bundle文件,同步创建AssetBundle对象,这是最快的创建方式。创建完成后只会在内存中创建较小的SerializedFile,而后续的AssetBundle.Load需要通过IO从磁盘中获取。
void LoadFromLocalFile()
{
AssetBundle bundle = AssetBundle.CreateFromFile(PathAssetBundle);
Instantiate(bundle.Load("Cube"));
} #endregion #region 第三种加载AB的方式,通过WWW加载 IEnumerator LoadFromWWW()
{
while (!Caching.ready)
yield return null;
WWW www = GetWWWInstance(false, PathAssetBundle);
yield return www; if (!string.IsNullOrEmpty(www.error))
{
Debug.Log(www.error);
yield break;
} AssetBundle bundle = www.assetBundle;
Instantiate(bundle.Load("Cube"));
} //WWW对象的获取方式有两种
//方式一 :加载Bundle文件并获取WWW对象,完成后会在内存中创建较大的WebStream
//方式二:加载Bundle文件并获取WWW对象,同时将解压形式的Bundle内容存入磁盘中作为缓存(如果该Bundle已在缓存中,则省去这一步),
// 完成后只会在内存中创建较小的SerializedFile,而后续的AssetBundle.Load需要通过IO从磁盘中的缓存获取。
WWW GetWWWInstance(bool isNew, string url)
{
WWW www = null;
if (isNew)
www = new WWW(url);
else
www = WWW.LoadFromCacheOrDownload(url, 0);
return www;
} #endregion
}