簡體   English   中英

如何通過Unity方法使用UDP

[英]How to use UDP with Unity methods

我創建了一個Cube對象並附加了此腳本。

using UnityEngine;
using System.Collections;

public class CubeMove : MonoBehaviour {
    void Start () {
    }

    void Update () {
    }

    public void Move () {
        Vector3 moveVector = new Vector3(10, 0, 0);
        transform.Translate(moveVector);
    }
}

我想使用UDP來控制多維數據集的移動,所以我創建了UDPManager。

using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class UDPManager : MonoBehaviour
{
    static UdpClient udp;
    Thread thread;

    public GameObject cube;
    public CubeMove cubemove;

    void Start ()
    {
        udp = new UdpClient(12345);
        cubemove = cube.GetComponent<CubeMove>();
        thread = new Thread(new ThreadStart(ThreadMethod));
        thread.Start();
    }

    void Update ()
    {
    }

    void OnApplicationQuit()
    {
        udp.Close();
        thread.Abort();
    }

    private void ThreadMethod()
    {
        while(true)
        {
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

            byte[] receiveBytes = udp.Receive(ref RemoteIpEndPoint); 
            string returnData = Encoding.ASCII.GetString(receiveBytes);
            Debug.Log(returnData);
            if (returnData == "1\n") {
                cube.SendMessage ("Move");
                // or
                cubemove.Move();

            }
        }
    } 
}

但是這些不適用於以下錯誤。

- SendMessage can only be called from the main thread.
- get_transform can only be called from the main thread.

收到udp命令時可以調用統一方法嗎?

您不能從另一個線程調用Unity API。 如何在Unity中使用線程:

1 啟動線程

2 在該新線程中處理輸入

3 告訴Unity您已完成處理。 您可以通過將全局boolean變量設置為truetrue output數據存儲在另一個全局變量中。

4 檢查boolean變量是否在Update()函數中更改。 如果設置為false則設置為false 過程輸出...

還要移動udp = new UdpClient(12345); Start函數到ThreadMethod函數。

static readonly object lockObject = new object();
string returnData = "";
bool precessData = false;

void Start ()
{
    cubemove = cube.GetComponent<CubeMove>();
    thread = new Thread(new ThreadStart(ThreadMethod));
    thread.Start();
}

void Update()
{
    if (precessData)
    {
        /*lock object to make sure there data is 
         *not being accessed from multiple threads at thesame time*/
        lock (lockObject)
        {
            precessData = false;
            cube.SendMessage("Move");
            // or
            cubemove.Move();

            //Process received data
            Debug.Log("Received: " + returnData);

            //Reset it for next read(OPTIONAL)
            returnData = "";
        }
    }
}

private void ThreadMethod()
{
    udp = new UdpClient(12345);
    while (true)
    {
        IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

        byte[] receiveBytes = udp.Receive(ref RemoteIpEndPoint);

        /*lock object to make sure there data is 
        *not being accessed from multiple threads at thesame time*/
        lock (lockObject)
        {
            returnData = Encoding.ASCII.GetString(receiveBytes);

            Debug.Log(returnData);
            if (returnData == "1\n")
            {
                //Done, notify the Update function
                precessData = true;
            }
        }
    }
}
using UnityEngine;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System;

public class UDPRT: ScriptableObject {
 static public string ReceivedMsg; // INPUT DATA
 static private UdpClient udpc;
 static IPEndPoint IP;
 static private object obj;
 static private AsyncCallback AC;
 static byte[] DATA;

 public static UDPRT CreateInstance(int Port) // RECEVE UDP
  {
   IP = new IPEndPoint(IPAddress.Any, Port);
   udpc = new UdpClient(Port);
   AC = new AsyncCallback(ReceiveIt);
   StartUdpReceive();
   return ScriptableObject.CreateInstance < UDPRT > ();
  }

 public static UDPRT CreateInstance(int Port, string Host, string msg) // SEND UDP
  {
   udpc = new UdpClient(Host, Port);
   AC = new AsyncCallback(SendIt);
   byte[] data = Encoding.UTF8.GetBytes(msg);
   udpc.BeginSend(data, data.Length, AC, obj);
   return ScriptableObject.CreateInstance < UDPRT > ();
  }

 static void ReceiveIt(IAsyncResult result) {
  DATA = (udpc.EndReceive(result, ref IP));
  Debug.Log(Encoding.UTF8.GetString(DATA));
  ReceivedMsg = Encoding.UTF8.GetString(DATA);
  StartUdpReceive();
 }

 static void SendIt(IAsyncResult result) {
  udpc.EndSend(result);
 }


 static void StartUdpReceive() {
  udpc.BeginReceive(AC, obj);
 }
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM