Unity UnityWebRequestAssetBundle.GetAssetBundle 请求跨域
时间: 2023-07-19 19:47:30 浏览: 49
UnityWebRequestAssetBundle.GetAssetBundle 请求跨域需要在服务器端设置相关的响应头信息,以允许跨域访问。具体的做法是在服务器端添加如下的响应头信息:
```
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With
```
其中,Access-Control-Allow-Origin 表示允许跨域访问的域名,* 表示允许所有域名访问;Access-Control-Allow-Methods 表示允许跨域访问的 HTTP 方法;Access-Control-Allow-Headers 表示允许跨域访问的 HTTP 头部信息。在服务器端添加这些响应头信息后,就可以使用 UnityWebRequestAssetBundle.GetAssetBundle 方法跨域请求资源了。
相关问题
public IEnumerator LoadAssetBundleByAll<T>(UIInfo uIInfo,Action<AssetBundle> loadCGCallBack, Action loadCallBack = null) where T : UnityEngine.Object { UnityWebRequest unityWeb = UnityWebRequestAssetBundle.GetAssetBundle(Application.streamingAssetsPath + "/" + uIInfo.groupName); yield return unityWeb.SendWebRequest(); if (unityWeb.error != null) { yield break; } AssetBundle ab = DownloadHandlerAssetBundle.GetContent(unityWeb); T obj = ab.LoadAsset<T>(uIInfo.objName); if (loadCGCallBack != null) { loadCGCallBack(ab); loadCGCallBack = null; } if (loadCallBack != null) { loadCallBack(); loadCallBack = null; } ab.Unload(false); yield return null; }
这段代码也是用于加载 Unity 引擎中的 Asset Bundle 资源文件,相比于之前的代码,这个函数会将整个 Asset Bundle 文件加载到内存中,并通过回调函数将其返回,而不仅仅是加载其中指定名称的资源文件。其中的泛型类型 T 用于指定要加载的资源类型,例如可以是音频、图片、场景等等。具体来说,这段代码也会从应用程序的 StreamingAssets 路径中获取指定的 Asset Bundle 文件,然后加载其中指定名称的资源文件并返回,并包括了回调函数的处理,以及最后释放 Asset Bundle 的资源。
Unity UnityWebRequestAssetBundle 添加相应头
如果你要在Unity中使用UnityWebRequestAssetBundle加载资源,并在请求中添加自定义响应头,可以使用UnityWebRequest的SetRequestHeader方法。以下是一个示例代码:
```csharp
IEnumerator LoadAssetBundle()
{
using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle("http://localhost:8080/WebGL/hualonglijiao.unity3d"))
{
// 添加自定义响应头
request.SetRequestHeader("My-Custom-Header", "header-value");
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError(request.error);
}
else
{
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
// 使用AssetBundle
}
}
}
```
在上面的代码中,我们使用UnityWebRequestAssetBundle.GetAssetBundle方法创建一个请求,然后调用SetRequestHeader方法添加自定义响应头。最后,我们使用DownloadHandlerAssetBundle.GetContent方法获取AssetBundle。