Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

c# - How to use UDP with Unity methods

I created a Cube object and attached this script.

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);
    }
}

I wanted to use UDP to control cube move, so I created 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
") {
                cube.SendMessage ("Move");
                // or
                cubemove.Move();

            }
        }
    } 
}

but these doesn't works with below errors.

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

Can I call unity methods when I receive udp command?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
")
            {
                //Done, notify the Update function
                precessData = true;
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...