当前位置:网站首页>Unity C# 网络学习(十)——UnityWebRequest(二)
Unity C# 网络学习(十)——UnityWebRequest(二)
2022-06-26 14:47:00 【帅_shuai_】
Unity C# 网络学习(十)——UnityWebRequest(二)
一.Unity提供的自定义获取数据DownLoadHandler
Unity帮我们定义好了一些相关的类,用于解析下载下来的数据的类,使用对应的类处理下载数据,他们就会在内部将下载的数据处理为对应的类型,方便使用
1.DownLoadHandlerBuffer(用于简单的数据存储,得到对应的二进制数据)
private IEnumerator DownLoadBuffer()
{
UnityWebRequest req = new UnityWebRequest("http://192.168.1.103:8080/Http_Server/xxx.jpg",
UnityWebRequest.kHttpVerbGET);
DownloadHandlerBuffer downloadHandlerBuffer = new DownloadHandlerBuffer();
req.downloadHandler = downloadHandlerBuffer;
yield return req.SendWebRequest();
if (req.result == UnityWebRequest.Result.Success)
{
byte[] buffer = downloadHandlerBuffer.data;
Debug.Log(buffer.Length);
Debug.Log("下载成功!");
}
else
{
Debug.Log("下载失败:"+req.result);
}
}
2.DownLoadHandlerFile(用于下载文件并将文件保存到磁盘,内存占用少)
private IEnumerator DownLoadFile()
{
UnityWebRequest req = new UnityWebRequest("http://192.168.1.103:8080/Http_Server/xxx.jpg", UnityWebRequest.kHttpVerbGET);
req.downloadHandler = new DownloadHandlerFile(Application.persistentDataPath + "/WebDownLoad.jpg");
yield return req.SendWebRequest();
Debug.Log(req.result);
}
3.DownLoadHandlerTexture(用于下载图片)
private IEnumerator DownLoadTexture()
{
UnityWebRequest req = new UnityWebRequest("http://192.168.1.103:8080/Http_Server/xxx.jpg", UnityWebRequest.kHttpVerbGET);
DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture();
req.downloadHandler = downloadHandlerTexture;
yield return req.SendWebRequest();
if (req.result == UnityWebRequest.Result.Success)
{
Debug.Log(downloadHandlerTexture.texture);
Debug.Log("下载成功!");
}
else
{
Debug.Log("下载失败:"+req.result);
}
}
4.DownLoadHandlerAssetBundle(用于提取AssetBundle)
private IEnumerator DownLoadAssetBundle()
{
UnityWebRequest req = new UnityWebRequest("http://192.168.1.103:8080/Http_Server/photo.ywj", UnityWebRequest.kHttpVerbGET);
DownloadHandlerAssetBundle downloadHandlerAssetBundle = new DownloadHandlerAssetBundle(req.url,0);
req.downloadHandler = downloadHandlerAssetBundle;
yield return req.SendWebRequest();
if (req.result == UnityWebRequest.Result.Success)
{
Debug.Log(downloadHandlerAssetBundle.assetBundle.name);
Debug.Log("下载成功!");
}
else
{
Debug.Log("下载失败:"+req.result);
}
}
5.DownLoadHandlerAudioClip(用于下载音频文件)
private IEnumerator DownLoadAudioClip()
{
UnityWebRequest req = new UnityWebRequest("http://192.168.1.103:8080/Http_Server/music.mp3", UnityWebRequest.kHttpVerbGET);
DownloadHandlerAudioClip downloadHandlerAudioClip = new DownloadHandlerAudioClip(req.url,AudioType.MPEG);
req.downloadHandler = downloadHandlerAudioClip;
yield return req.SendWebRequest();
if (req.result == UnityWebRequest.Result.Success)
{
Debug.Log(downloadHandlerAudioClip.audioClip);
Debug.Log("下载成功!");
}
else
{
Debug.Log("下载失败:"+req.result);
}
}
二.自定义DownLoadHandler去处理数据
- 当我们对数据有需要进行拓展时,可以继承自DownloadHandlerScript类对其拓展使用
public class CustomDownLoadFileHandler : DownloadHandlerScript
{
private string _savePath;
private byte[] _cacheBytes;
private int _index;
public CustomDownLoadFileHandler() : base()
{
}
public CustomDownLoadFileHandler(byte[] bytes) : base(bytes)
{
}
public CustomDownLoadFileHandler(string path) : base()
{
this._savePath = path;
}
protected override byte[] GetData()
{
return _cacheBytes;
}
//从网络收到数据后,每帧会调用的方法
protected override bool ReceiveData(byte[] buffer, int dataLength)
{
buffer.CopyTo(_cacheBytes,_index);
_index += dataLength;
return true;
}
//从服务器收到contentLength标头时会调用
protected override void ReceiveContentLengthHeader(ulong contentLength)
{
_cacheBytes = new byte[contentLength];
}
//消息收完了,会自动调用的方法
protected override void CompleteContent()
{
File.WriteAllBytes(_savePath,_cacheBytes);
}
}
进行测试
private IEnumerator CustomDownLoadFile()
{
UnityWebRequest unityWebRequest = new UnityWebRequest("http://192.168.1.103:8080/Http_Server/xxx.jpg",
UnityWebRequest.kHttpVerbGET);
unityWebRequest.downloadHandler = new CustomDownLoadFileHandler(Application.persistentDataPath+"/zzsCustom.jpg");
yield return unityWebRequest.SendWebRequest();
Debug.Log(unityWebRequest.result);
}
三.自定义DownLoadHandler练习处理
public class DownLoadHandlerMsg : DownloadHandlerScript
{
private byte[] _cacheBuffer;
private int _index;
private MsgBase _msgBase;
public DownLoadHandlerMsg()
{
}
public T GetMsg<T>() where T : MsgBase
{
return _msgBase as T;
}
protected override byte[] GetData()
{
return _cacheBuffer;
}
protected override void ReceiveContentLengthHeader(ulong contentLength)
{
_cacheBuffer = new byte[contentLength];
}
protected override bool ReceiveData(byte[] buffer, int dataLength)
{
buffer.CopyTo(_cacheBuffer,_index);
_index += dataLength;
return true;
}
protected override void CompleteContent()
{
int index = 0;
int msgId = BitConverter.ToInt32(_cacheBuffer,index);
index += 4;
int msgLength = BitConverter.ToInt32(_cacheBuffer, index);
index += 4;
switch (msgId)
{
case 1001:
_msgBase = new PlayerMsg();
_msgBase.Reading(_cacheBuffer, index);
break;
}
Debug.Log(_msgBase == null ? "消息Id错误!" : "消息解析成功!");
}
}
测试代码
private IEnumerator Start()
{
UnityWebRequest unityWebRequest = new UnityWebRequest("", UnityWebRequest.kHttpVerbGET);
unityWebRequest.downloadHandler = new DownLoadHandlerMsg();
yield return unityWebRequest.SendWebRequest();
Debug.Log(unityWebRequest.result);
}
边栏推荐
- Extended hooks
- 关于 selenium.common.exceptions.WebDriverException: Message: An unknown server-side error 解决方案(已解决)
- Oracle ASMM and AMM
- 使用宝塔面板部署flask环境
- Attention meets Geometry:几何引导的时空注意一致性自监督单目深度估计
- Electron
- cluster addslots建立集群
- 15 bs对象.节点名称.节点名称.string 获取嵌套节点内容
- R语言epiDisplay包的dotplot函数通过点图的形式可视化不同区间数据点的频率、使用by参数指定分组参数可视化不同分组的点图分布、使用cex.X.axis参数指定X轴轴刻度数值标签字体的大小
- Solution to the upper limit of TeamViewer display devices
猜你喜欢

This is the graceful file system mounting method, which is effective through personal testing

Electron

详解C语言编程题:任意三条边能否构成三角形,输出该三角形面积并判断其类型

【雲原生】 ”人人皆可“ 編程的無代碼 iVX 編輯器

Combat readiness mathematical modeling 32 correlation analysis 2

【云原生】 ”人人皆可“ 编程的无代码 iVX 编辑器

Halcon C# 设置窗体字体,自适应显示图片

NAACL2022:(代码实践)好的视觉引导促进更好的特征提取,多模态命名实体识别(附源代码下载)...

The annual salary of 500000 is one line, and the annual salary of 1million is another line

Question bank and answers of the latest Guizhou construction eight (Mechanics) simulated examination in 2022
随机推荐
15 bs对象.节点名称.节点名称.string 获取嵌套节点内容
[async/await] - the final solution of asynchronous programming
Bank of Beijing x Huawei: network intelligent operation and maintenance tamps the base of digital transformation service
Kubernetes的pod调度
NAACL2022:(代码实践)好的视觉引导促进更好的特征提取,多模态命名实体识别(附源代码下载)...
券商经理给的开户链接安全吗?找谁可以开户啊?
The intersect function in the dplyr package of R language obtains the data lines that exist in both dataframes and the data lines that cross the two dataframes
The R language cartools package divides data, the scale function scales data, and the KNN function of the class package constructs a k-nearest neighbor classifier
Optimizing for vectorization
The engine "node" is inconsistent with this module
R语言epiDisplay包的dotplot函数通过点图的形式可视化不同区间数据点的频率、使用by参数指定分组参数可视化不同分组的点图分布、使用cex.X.axis参数指定X轴轴刻度数值标签字体的大小
What is the ranking of Guosen Securities? Is it safe to open a stock account?
Datasets dataset class (2)
Declaration and assignment of go variables
Is it safe to open a stock account with the account manager online??
Redis事务与watch指令
15 BS object Node name Node name String get nested node content
【 Native cloud】 Éditeur ivx Programmable par tout le monde
Atcoder bit operation & Conclusion + formula derivation
Sharing ideas for a quick switch to an underlying implementation