Unity C# 网络学习(十)——UnityWebRequest(二)

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);
}
### 集成YOLOv8到Unity进行物体检测 为了在Unity环境中实现YOLOv8的物体检测功能,可以采用几种不同的方法来完成这一目标。一种常见的方式是通过中间服务器作为桥梁,在该服务器上运行YOLOv8模型并处理来自Unity客户端发送过来的图像数据;另一种方式则是尝试直接在Unity项目内嵌入YOLOv8推理引擎。 #### 方法一:基于Web API的服务端部署方案 创建一个RESTful Web服务接口用于接收图片请求,并返回标注后的结果给Unity应用。此过程涉及以下几个方面: - **训练好的YOLOv8模型**:确保已经拥有经过适当训练能够满足特定需求的YOLOv8权重文件[^4]。 - **Flask/Django等框架搭建API**:利用Python web框架快速构建起能调用YOLOv8预测函数的服务端口[^5]。 ```python from flask import Flask, request, jsonify import torch from PIL import Image app = Flask(__name__) model = torch.hub.load('ultralytics/yolov8', 'custom', path='path/to/best.pt') @app.route('/predict', methods=['POST']) def predict(): file = request.files['image'] img_bytes = file.read() results = model(Image.open(io.BytesIO(img_bytes)), size=640) return jsonify(results.pandas().xyxy[0].to_dict(orient="records")) if __name__ == '__main__': app.run(host='0.0.0.0') ``` - **Unity侧HTTP通信模块编写**:使用C#脚本发起网络请求并将接收到的数据解析出来展示于游戏视窗之中[^6]。 ```csharp using UnityEngine; using System.Collections; using UnityEngine.Networking; public class ObjectDetection : MonoBehaviour { private IEnumerator Start() { WWWForm form = new WWWForm(); Texture2D texture = ...; // 获取当前帧纹理 byte[] bytes = texture.EncodeToPNG(); form.AddBinaryData("image", bytes); UnityWebRequest www = UnityWebRequest.Post("http://localhost:5000/predict", form); yield return www.SendWebRequest(); if (www.result != UnityWebRequest.Result.Success) { Debug.LogError(www.error); } else { string jsonResponse = www.downloadHandler.text; // 解析JSON响应... } } } ``` #### 方法:本地化解决方案——借助ML-Agents或其他插件支持 对于希望减少延迟或者离线工作的开发者来说,可能更倾向于探索如何让YOLOv8直接跑在Unity内部的可能性。这通常意味着要寻找合适的机器学习代理工具包(如ML-Agents),或是其他形式的支持库帮助移植深度神经网络Unity平台之上。不过需要注意的是,这种方法可能会遇到性能瓶颈以及兼容性挑战等问题[^7]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值