AssetBundle中的資源加載有兩種,分別是從本地加載,一種是訪問服務器進行加載,目前Unity中可以把兩個整合到一起,只用該少量的代碼就能實現從本地加載,到訪問服務器來對資源的加載。下面介紹的就是這種。
IEnumerator LoadFromUnityWebRequest()
{
//從本地
string url = @"file:///D:\vc\U3D\Json_Demo\AssetsBundle\cube.prefab";
//從服務器中
string urlWeb = @"http://localhost/AssetsBundle/cube.prefab";
//訪問
UnityWebRequest request = UnityWebRequest.GetAssetBundle(urlWeb);
//下載
yield return request.SendWebRequest();
//從本地加載
AssetBundle ab1 = DownloadHandlerAssetBundle.GetContent(request);
//服務器端加載
AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
//加載所有cube
GameObject cubePre = ab.LoadAsset<GameObject>("cube");
//加載所有的對象,讓其複製出來
Object[] obj = ab.LoadAllAssets();
foreach (var o in obj)
{
Instantiate(o);
}
}
注意,得加個using UnityEngine.Networking 才能調用UnityWebRequest方法。