unity +udp通讯视频传输解决摄像机设置找不到问题
using UnityEngine;
using System.Net.Sockets;
public class VideoSender : MonoBehaviour
{
[Header("摄像机设置")]
public Camera captureCamera;
public int targetWidth = 640;
public int targetHeight = 360;
[Header("网络设置")]
public string remoteIP = "192.168.0.78"; // 接收端 IP根据自己需要配置
public int remotePort = 8888;// 接收端端口根据自己需要配置
[Header("发送帧率")]
public int fps = 15;
private RenderTexture renderTexture;
private Texture2D readTexture;
private UdpClient udpClient;
private float timer;
void Start()
{
if (captureCamera == null)
{
Debug.LogError("❌ 请在 Inspector 中指定 captureCamera!");
enabled = false;
return;
}
renderTexture = new RenderTexture(targetWidth, targetHeight, 16);
readTexture = new Texture2D(targetWidth, targetHeight, TextureFormat.RGB24, false);
udpClient = new UdpClient();
timer = 0;
}
void Update()
{
timer += Time.deltaTime;
if (timer >= 1f / fps)
{
timer = 0;
SendFrame();
}
}
void SendFrame()
{
if (captureCamera == null || !captureCamera.enabled || !captureCamera.gameObject.activeInHierarchy)
{
Debug.LogWarning("⚠️ 摄像机未启用或未激活,跳过本帧!");
return;
}
// 设置渲染目标并渲染
captureCamera.targetTexture = renderTexture;
RenderTexture.active = renderTexture;
captureCamera.Render();
// 从渲染结果中读取图像
readTexture.ReadPixels(new Rect(0, 0, targetWidth, targetHeight), 0, 0);
readTexture.Apply();
RenderTexture.active = null;
captureCamera.targetTexture = null;
// 编码为 JPEG
byte[] jpgBytes = readTexture.EncodeToJPG(40); // 压缩率 0~100
// UDP 发送(不超过 65KB)
if (jpgBytes.Length < 65000)
{
udpClient.Send(jpgBytes, jpgBytes.Length, remoteIP, remotePort);
}
else
{
Debug.LogWarning("⚠️ 图片数据太大,需分包或切换 TCP!");
}
}
void OnApplicationQuit()
{
udpClient.Close();
}
}
unity中创建空物体吧脚本VideoSender添加在空物体上,
更多推荐

所有评论(0)