从服务器加载AssetBundle包

搭建服务器


本文使用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物体


猜你喜欢

转载自www.cnblogs.com/gitctrls/p/10542367.html