2014-09-02 54 views
4

我想使用套接字将UDP包读入Unity3d。 UDP包由另一个不是Unity应用程序的C#应用​​程序发送。因此,我将以下脚本(original source)附加到我的一个游戏对象中。不幸的是,当我运行我的项目时,Unity死机。谁能告诉我为什么?Unity3d和UdpClient

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#应用程序包含游戏逻辑。我需要传输的数据包括所有可能的控制状态,例如不同玩家/对象的位置/方向等。两个应用程序都在同一台机器上运行。

回答

1

您的接收在默认情况下处于阻止状态,因此更新呼叫正在等待接收完成。

client.Client.Blocking = false; 
1

添加超时接收

client.Client.ReceiveTimeout = 1000; 

创建您的客户端后添加此