由于Unity Manual文档的UnityWebRequest相关api未更新,相关方法已经弃用。特写此博客记录最新的使用方法。
旧的方法
IEnumerator InstantiateObject() {
string uri = "file:///" + Application.dataPath + "/AssetBundles/" + assetBundleName;
UnityEngine.Networking.UnityWebRequest request = UnityEngine.Networking.UnityWebRequest.GetAssetBundle(uri, 0);
yield return request.Send();
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
GameObject cube = bundle.LoadAsset<GameObject>("Cube");
GameObject sprite = bundle.LoadAsset<GameObject>("Sprite");
Instantiate(cube); Instantiate(sprite);
}
//新的加载AB的方式:
IEnumerator InstantiateObject() {
string path = @"http://localhost/AssetBundle/rock.zl";
UnityWebRequest request = UnityWebRequest.Get(path);
yield return request.SendWebRequest();
while (request.isHttpError)
{
Debug.LogError(TAG+"ERROR"+request.error);
yield return null;
}
while (!request.isDone)
{
yield return null;
}
byte[] results = request.downloadHandler.data;
AssetBundle ab = AssetBundle.LoadFromMemory(results);
//实例化
GameObject obj = ab.LoadAsset<GameObject>("Rock");
Instantiate(obj);
}