Unity3D资源异步加载——图片音视频资源加载
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity3D资源异步加载——图片音视频资源加载相关的知识,希望对你有一定的参考价值。
这几天一直做优化的事情,对于资源这一块优化,资源异步加载作为首选,因2018之后版本中弃用了WWW请求,所以今天我们以UnityWebRequest 请求方式介绍,基本上是一个整理。using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class ResourceLoad : MonoBehaviour
{
/// <summary>
/// 单例
/// </summary>
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<ResourceLoad>();
if (null == _instance)
{
_instance = singleton.AddComponent<ResourceLoad>();
}
}
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--//对请求分装
/// <summary>
/// get请求
/// </summary>
/// <param name="url"></param>
/// <param name="actionResult"></param>
public void WebquestGet(string url, System.Action<bool, string> actionResult)
{
StartCoroutine(_Get(url, actionResult));
}
/// <summary>
/// Sprite请求
/// </summary>
/// <param name="url"></param>
/// <param name="actionResult"></param>
public void WebquestGet(string url, System.Action<bool, string, Sprite> actionResult)
{
StartCoroutine(_GetTexture(url, actionResult));
}
// .
// .
// .
// . 省略
#endregion
#region --- 网络请求
/// <summary>
/// GET请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="action">请求发起后处理回调结果的委托</param>
/// <returns></returns>
IEnumerator _Get(string url, System.Action<bool, string> 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);
}
}
}
/// <summary>
/// 请求文件byte
/// </summary>
/// <param name="url"></param>
/// <param name="action">请求发起后处理回调结果的委托,处理请求结果的byte数组</param>
/// <returns></returns>
IEnumerator _GetBytes(string url, System.Action<bool, string, byte[]> 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);
}
}
}
/// <summary>
/// 请求Sprite和图片
/// </summary>
/// <param name="url">图片地址‘</param>
/// <param name="action">请求发起后处理回调结果的委托,处理请求结果的图片</param>
/// <returns></returns>
IEnumerator _GetTexture(string url, System.Action<bool, string, Sprite> 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);
}
}
}
/// <summary>
/// 请求服务器地址上的音效
/// </summary>
/// <param name="url">没有音频地址</param>
/// <param name="actionResult">请求发起后处理回调结果的委托,处理请求结果的MovieTexture</param>
/// <param name="audioType">音效类型</param>
/// <returns></returns>
IEnumerator _GetAudioClip(string url, System.Action<bool, string, AudioClip> 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);
}
}
}
/// <summary>
/// 向服务器提交post请求
/// </summary>
/// <param name="url">服务器请求目标地址</param>
/// <param name="formData">form表单参数</param>
/// <returns></returns>
IEnumerator _Post(string url, string formData, System.Action<bool, string> 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);
}
}
}
/// <summary>
/// 设置表头和发送信息
/// </summary>
/// <param name="quest"></param>
/// <param name="info"></param>
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<IMultipartFormSection> formData = new List<IMultipartFormSection>();
//formData.Add(new MultipartFormDataSection("field1=foo&field2=bar"));
//formData.Add(new MultipartFormFileSection("my file data", "myfile.txt"));
}
#endregion
}
以上是关于Unity3D资源异步加载——图片音视频资源加载的主要内容,如果未能解决你的问题,请参考以下文章
Unity3D资源异步加载——Addressables资源异步加载
Unity3D资源异步加载——AssetBundle资源打包加载
Unity3d C# 实现AA包(Addressables)资源热更新的多个包异步加载并显示加载实时进度功能(含源码)