從服務器加載AssetBundle包
阿新 • • 發佈:2019-03-16
document void ref collect .net 安裝完成 ack 參數 輸入
窗口不能關掉,否則會停止服務,如果需要停止服務可以按Ctrl+C。
搭建服務器
本文使用Node.js來搭建一個本地服務器。
首先,安裝Node.js。
在安裝完成後再安裝http-server,在命令行輸入:
npm install http-server -g
等待安裝完成後,在命令行輸入以下命令即可開啟服務(具體使用方法可參考http-server使用):
http-server [path] [options]
其中,[path]為開啟服務的路徑,[options]為命令參數,這兩個參數也可以不填寫,[path]不填寫默認為當前路徑。
如圖,在~/Documents/LocalServer路徑下開啟http-server服務(在命令行中切換到LocalServer路徑後,輸入htttp-server)
窗口不能關掉,否則會停止服務,如果需要停止服務可以按Ctrl+C。
上傳文件到服務器中
由於使用本地服務器,所以將生成的AssetBundle文件拷貝到該路徑下即可
從服務器加載AssetBundle資源
參考代碼:
using System.Collections; using UnityEngine; using UnityEngine.Networking; public class AssetBundleTest : MonoBehaviour { private void Awake() { StartCoroutine(LoadWoodFromWeb()); } private IEnumerator LoadWoodFromWeb() { // 使用using ,這段代碼完成後將會自動調用類的Dispose方法,相當於uwr.Dispose() using (UnityWebRequest uwr = UnityWebRequest.GetAssetBundle("http://localhost:8080/AssetBundles/wood")) { yield return uwr.SendWebRequest(); //向服務器發送請求並處理響應 AssetBundle ab = DownloadHandlerAssetBundle.GetContent(uwr); //DownloadHandlerAssetBundle專門用於處理AssetBundle,GetContent將會返回一個AssetBundle(或者null) GameObject wood1 = ab.LoadAsset<GameObject>("Wood1"); Instantiate(wood1); ab.Unload(false); } } }
將這段代碼掛到場景中運行,就可以看到成功在場景中加載了Wood1物體
從服務器加載AssetBundle包