这几天一直做优化的事情,对于资源这一块优化,资源异步加载作为首选,因2018之后版本中弃用了WWW请求,所以今天我们以UnityWebRequest 请求方式介绍,基本上是一个整理。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class ResourceLoad : MonoBehaviour
{
///
/// 单例
///
private static ResourceLoad _instance = null;
public static ResourceLoad Instance {
get {
if(null == _instance)
{
GameObject singleton = (GameObject)UnityEngine.Object.FindObjectOfType(typeof(GameObject));
if(null == singleton)
{
singleton = new GameObject("Singleton");
DontDestroyOnLoad(singleton);
}
_instance = singleton.GetComponent();
if (null == _instance)
{
_instance = singleton.AddComponent();
}
}
return _instance;
}
}
/*UnityWebRequests处理与Web服务器的HTTP通信流。
* 其他对象-特别是DownloadHandler和UploadHandler-分别控制数据的下载和上传。
* 为了方便起见,提供了一组静态函数。这些将返回为许多常见用例正确配置的UnityWebRequest对象。请参阅: Get,Post,Put,GetTexture。
* 可以对下面属性了解
* responseCode 服务器返回的数字HTTP响应代码,例如200、404或500。(只读)
* timeout 设置UnityWebRequest以尝试在超时秒数过去后中止。
* downloadProgress 返回介于0.0和1.0之间的浮点值,指示从服务器下载正文数据的进度。(只读)
* 返回介于0.0和1.0之间的浮点值,指示将主体数据上传到服务器的进度。
* useHttpContinue 确定此UnityWebRequest是否在其传出请求标头中包含Expect:100-Continue。(默认值:true)。
* SendWebRequest 开始与远程服务器通信。
* SetRequestHeader 将HTTP请求标头设置为自定义值。
* Head Creates a UnityWebRequest configured to send a HTTP HEAD request.
*/
#region--//对请求分装
///
/// get请求
///
///
///
public void WebquestGet(string url, System.Action actionResult)
{
StartCoroutine(_Get(url, actionResult));
}
///
/// Sprite请求
///
///
///
public void WebquestGet(string url, System.Action actionResult)
{
StartCoroutine(_GetTexture(url, actionResult));
}
// .
// .
// .
// . 省略
#endregion
#region --- 网络请求
///
/// GET请求
///
/// 请求地址
/// 请求发起后处理回调结果的委托
///
IEnumerator _Get(string url, System.Action actionResult)
{
using (UnityWebRequest quest = UnityWebRequest.Get(url))
{
yield return quest.SendWebRequest();
string msg = "";
if (!(quest.isNetworkError || quest.isHttpError))
{
msg = quest.downloadHandler.text;
}
else
{
msg = quest.error;
}
if (actionResult != null)
{
actionResult.Invoke(quest.isHttpError, msg);
}
}
}
///
/// 请求文件byte
///
///
/// 请求发起后处理回调结果的委托,处理请求结果的byte数组
///
IEnumerator _GetBytes(string url, System.Action actionResult)
{
using (UnityWebRequest quest = new UnityWebRequest(url))
{
DownloadHandlerFile downloadFile = new DownloadHandlerFile(url);
quest.downloadHandler = downloadFile;
yield return quest.SendWebRequest();
byte[] bytes = null;
string text = null;
if (!(quest.isNetworkError || quest.isHttpError))
{
bytes = downloadFile.data;
}
else
{
text = quest.error;
}
if (actionResult != null)
{
actionResult.Invoke((quest.isNetworkError || quest.isHttpError), text, bytes);
}
}
}
///
/// 请求Sprite和图片
///
/// 图片地址'
/// 请求发起后处理回调结果的委托,处理请求结果的图片
///
IEnumerator _GetTexture(string url, System.Action actionResult)
{
using (UnityWebRequest quest = UnityWebRequestTexture.GetTexture(url)) // 或者直接用 new UnityWebRequest(url)
{
//DownloadHandlerTexture downloadTexture = new DownloadHandlerTexture(true);
//quest.downloadHandler = downloadTexture;
yield return quest.SendWebRequest();
string text = null;
Sprite sprite = null;
if (!(quest.isNetworkError || quest.isHttpError))
{
Texture2D texture = DownloadHandlerTexture.GetContent(quest); //downloadTexture.texture;
sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
else
{
text = quest.error;
}
if (actionResult != null)
{
actionResult.Invoke((quest.isNetworkError || quest.isHttpError), text, sprite);
}
}
}
///
/// 请求服务器地址上的音效
///
/// 没有音频地址
/// 请求发起后处理回调结果的委托,处理请求结果的MovieTexture
/// 音效类型
///
IEnumerator _GetAudioClip(string url, System.Action actionResult, AudioType audioType = AudioType.WAV)
{
using (UnityWebRequest quest = UnityWebRequest.Get(url))
{
DownloadHandlerAudioClip downloadAudioClip = new DownloadHandlerAudioClip(url, audioType);
quest.downloadHandler = downloadAudioClip;
yield return quest.SendWebRequest();
AudioClip audioClip = null;
string text = null;
if (!(quest.isNetworkError || quest.isHttpError))
{
audioClip = downloadAudioClip.audioClip;
}
else
{
text = quest.error;
}
if (actionResult != null)
{
actionResult.Invoke((quest.isNetworkError || quest.isHttpError), text, audioClip);
}
}
}
///
/// 向服务器提交post请求
///
/// 服务器请求目标地址
/// form表单参数
///
IEnumerator _Post(string url, string formData, System.Action actionResult)
{
using (UnityWebRequest quest = UnityWebRequest.Post(url, formData))
{
//发送数据
setWebRequest(quest, formData);
yield return quest.SendWebRequest();
string text = "";
if (!(quest.isNetworkError || quest.isHttpError))
{
text = quest.downloadHandler.text;
}
else
{
text = quest.error;
}
if (actionResult != null)
{
actionResult.Invoke(quest.isHttpError, text);
}
}
}
///
/// 设置表头和发送信息
///
///
///
void setWebRequest(UnityWebRequest quest, string info)
{
//设置发送表头信息
quest.SetRequestHeader("Content-Type", "application/json");
//设置发送的信息
Object objectInfo = null;//(设置info 类结构对象信息)
string jsonId = JsonUtility.ToJson(objectInfo);
byte[] wForm = System.Text.Encoding.UTF8.GetBytes(jsonId);
quest.uploadHandler = new UploadHandlerRaw(wForm);
quest.downloadHandler = new DownloadHandlerBuffer();
//或者
//List formData = new List();
//formData.Add(new MultipartFormDataSection("field1=foo&field2=bar"));
//formData.Add(new MultipartFormFileSection("my file data", "myfile.txt"));
}
#endregion
}