How to use UDP with Unity methods

后端 未结 2 1418
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-18 09:31

I created a Cube object and attached this script.

using UnityEngine;
using System.Collections;

public class CubeMove : MonoBehaviour {
    void Start () {
          


        
相关标签:
2条回答
  • 2020-12-18 10:24

    You can't call Unity API from another Thread. How to use Thread in Unity:

    1. Start Thread

    2. Process Input in that new thread

    3. Tell Unity that you are done processing. You can do this by setting a global boolean variable to true. Store output data in another global variable.

    4. Check if the the boolean variable changed in the Update() function. Set it false if it did. Process output...

    Also move udp = new UdpClient(12345); from the Start function to the ThreadMethod function.

    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;
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-18 10:28
    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);
     }
    } 
    
    0 讨论(0)
提交回复
热议问题