UnityWebRequest类配合IIS服务器实现资源的远程加载
事情的起因是做一demo时想要在Unity工程运行时访问局域网内其他设备的资源(AssetBundle),搭建好IIS后却发现怎么都访问不到所需要的资源(确认路径等信息无错),后来发现原来是文件后缀名的原因。
AssetBundle类
将所需文件打包成一AssetBundle类,以供后续访问。参考:
Unity使用AssetBundle(AB包)实现资源的打包,加载和卸载
需要注意的是,在上面文章中有一步骤是设置AssetBundle文件的后缀名,如下:
在这里我设置了AssetBundle文件的文件名是prefabs,后缀是.assetbundle,此后缀名可随意设置,但后续和IIS的配置相关。
UnityWebRequest类
类用法网上资源很多,此地不多赘述,附一链接:
Unity之UnityWebRequest和使用
附一代码,其实现了读取局域网服务器下的AssetBundle文件,并读取其中的预制体,再看不明白请让chatgpt帮你解释:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class UnityWebRequestTest : MonoBehaviour
{
// Start is called before the first frame update
public AssetBundle bundle;
GameObject go;
void Start()
{
Debug.Log("ee");
StartCoroutine(LoadAssetBundleFromURL("http://192.168.3.6:443/meshBased/prefabs.assetbundle"));
//StartCoroutine(LoadAssetBundleFromURL("http://192.168.3.6:80/prefabs.assetbundle"));
}
// Update is called once per frame
void Update()
{
}
IEnumerator LoadAssetBundleFromURL(string url)
{
UnityWebRequest uwr=UnityWebRequestAssetBundle.GetAssetBundle(url);
yield return uwr.SendWebRequest();
if (uwr.result == UnityWebRequest.Result.Success)
{
bundle = DownloadHandlerAssetBundle.GetContent(uwr);
Debug.Log("读取AssetBundle成功");
go = bundle.LoadAsset<GameObject>("GameObject");
Debug.Log(go == null);
Instantiate(go, new Vector3(0, 0, 0), Quaternion.identity);
}
else
{
Debug.Log("下载AssetBundle出错: " + uwr.error);
}
bundle.Unload(false);
}
}
IIS服务器搭建
IIS的搭建过程教程很多,也很方便,此地不多赘述,附一链接:
使用IIS搭建本地Web服务器(手把手教程)
注意事项
如果你按照上述步骤完成整个过程之后,运行Unity脚本,那大概率是不会成功的,可能会报HTTP 404 NOT FOUND错误,原因其实是我们之前设置的.assetbundle后缀名并不在IIS的MIME扩展类型中,需要手动添加一下(问题虽小,发现却不易)。
如何添加参考:
IIS 之 添加MIME扩展类型及常用的MIME类型列表