如果 材质 和 Prefab 分别打包,则需要先拆材质包再拆Prefab包
代码如下
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class LoadAB : MonoBehaviour
{
IEnumerator Start()
{
string path = "AB/scene/zxw.1";//路径
//通过本地文件加载
//AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(path);//通过文件路径取得A包资源
//yield return request;//等待load加载完成并返回
//AssetBundle ab = request.assetBundle;//取得对象
//通过内存加载
//异步 需要等待加载完成 需要引入协程IEnumerator
//AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path));
//yield return request;
//AssetBundle ab = request.assetBundle;
//同步 不需要等待加载完成 29行 = 23-25行
//AssetBundle ab = AssetBundle.LoadFromMemory(File.ReadAllBytes(path));
//通过WWW加载 如果有错误 不会出现异常 常加一个安全校验
//while (Caching.ready == false)
//{
// yield return null;
//}
////WWW www = WWW.LoadFromCacheOrDownload(@"file:///D:\unity\AssetBundle\AB\scene\zxw.1", 1);//(路径(前面加一个@符号,注意为两或三个反斜杠),版本号)
////通过网络加载(搭建简单的Server服务器)
//WWW www = WWW.LoadFromCacheOrDownload(@"http://localhost/AB/scene/zxw.1", 1);//(路径(前面加一个@符号,注意为两或三个反斜杠),版本号)
//yield return www;
////安全校验
//if (string.IsNullOrEmpty(www.error) == false)//如果为空或者空字符串
//{
// Debug.Log(www.error);
// yield break;//中断协程
//}
//AssetBundle ab = www.assetBundle;//取得对象
//使用UnityWebRequest加载
string uri = @"file:///D:\unity\AssetBundle\AB\scene\zxw.1";//声明统一资源路径(文件)
//string uri = @"http://localhost/AB/scene/zxw.1";//声明统一资源路径(Server路径)
UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(uri);//指定uri
yield return request.Send();
//AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);//取得对象
//或
AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;//将下载的资源转换为ab资源利用
//加载操作
GameObject GameAB = ab.LoadAsset<GameObject>("Sphere");//加载A包资源 注意这里是Prefab的名字
Instantiate(GameAB);//实例化到场景当中
}
}