2014-09-02 45 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; 

創建您的客戶端後添加此