[英]Unity3d and UdpClient
我想使用套接字将UDP包读入Unity3d。 UDP软件包由另一个C#应用程序(不是Unity App)发送。 因此,我将以下脚本( 原始源代码 )附加到我的一个游戏对象上。 不幸的是,当我运行项目时,Unity冻结了。 谁能告诉我为什么?
using UnityEngine;
using System.Collections;
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class InputUDP : MonoBehaviour
{
// read Thread
Thread readThread;
// udpclient object
UdpClient client;
// port number
public int port = 9900;
// UDP packet store
public string lastReceivedPacket = "";
public string allReceivedPackets = ""; // this one has to be cleaned up from time to time
// start from unity3d
void Start()
{
// create thread for reading UDP messages
readThread = new Thread(new ThreadStart(ReceiveData));
readThread.IsBackground = true;
readThread.Start();
}
// Unity Update Function
void Update()
{
// check button "s" to abort the read-thread
if (Input.GetKeyDown("q"))
stopThread();
}
// Unity Application Quit Function
void OnApplicationQuit()
{
stopThread();
}
// Stop reading UDP messages
private void stopThread()
{
if (readThread.IsAlive)
{
readThread.Abort();
}
client.Close();
}
// receive thread function
private void ReceiveData()
{
client = new UdpClient(port);
while (true)
{
try
{
// receive bytes
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
// encode UTF8-coded bytes to text format
string text = Encoding.UTF8.GetString(data);
// show received message
print(">> " + text);
// store new massage as latest message
lastReceivedPacket = text;
// update received messages
allReceivedPackets = allReceivedPackets + text;
}
catch (Exception err)
{
print(err.ToString());
}
}
}
// return the latest message
public string getLatestPacket()
{
allReceivedPackets = "";
return lastReceivedPacket;
}
}
注意:我想使用IPC将我们的游戏逻辑与Unity相连接(使用unity作为渲染引擎)。 C#应用程序包含游戏逻辑。 我需要传输的数据包括所有可能的控制状态,例如不同玩家/对象的位置/方向等。两个应用程序都在同一台机器上运行。
默认情况下,您的接收处于阻止状态-因此,更新呼叫正在等待接收完成。
创建客户端后添加以下内容:
client.Client.Blocking = false;
添加接收超时
client.Client.ReceiveTimeout = 1000;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.