//以下是一个使用UDP协议进行结构体数据收发的Unity C#脚本示例:
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
// 定义一个结构体
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MyStruct
{
public int intValue;
public float floatValue;
public bool boolValue;
}
public class UdpStructSender : MonoBehaviour
{
// 发送目标IP和端口
public string sendIp = "127.0.0.1";
public int sendPort = 1234;
// 接收端口
public int receivePort = 4321;
// 发送间隔
public float sendInterval = 0.1f;
// 结构体数据
private MyStruct myStruct;
// 发送器和接收器
private UdpClient sender;
private UdpClient receiver;
// 发送数据
private void SendData()
{
// 将结构体数据转换为字节数组
byte[] data = StructToBytes(myStruct);
// 发送数据
sender.Send(data, data.Length, sendIp, sendPort);
}
// 接收数据
private void ReceiveData()
{
// 接收数据
IPEndPoint remoteIp = new IPEndPoint(IPAddress.Any, 0);
byte[] data = receiver.Receive(ref remoteIp);
// 将字节数组转换为结构体数据
myStruct = BytesToStruct<MyStruct>(data);
}
// 将结构体转换为字节数组
private byte[] StructToBytes<T>(T structure) where T : struct
{
int size = Marshal.SizeOf(structure);
byte[] buffer = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structure, ptr, true);
Marshal.Copy(ptr, buffer, 0, size);
}
finally
{
Marshal.FreeHGlobal(ptr);
}
return buffer;
}
// 将字节数组转换为结构体
private T BytesToStruct<T>(byte[] buffer) where T : struct
{
T structure = default(T);
int size = Marshal.SizeOf(structure);
if (size > buffer.Length)
{
return structure;
}
IntPtr ptr = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(buffer, 0, ptr, size);
structure = (T)Marshal.PtrToStructure(ptr, structure.GetType());
}
finally
{
Marshal.FreeHGlobal(ptr);
}
return structure;
}
// 初始化
private void Start()
{
// 创建发送器和接收器
sender = new UdpClient();
receiver = new UdpClient(receivePort);
// 设置结构体数据
myStruct.intValue = 10;
myStruct.floatValue = 3.14f;
myStruct.boolValue = true;
}
// 发送和接收数据
private void Update()
{
// 发送数据
SendData();
// 接收数据
ReceiveData();
}
// 销毁发送器和接收器
private void OnDestroy()
{
sender.Close();
receiver.Close();
}
}