如何在 Unity 方法中使用 UDP [英] How to use UDP with Unity methods

查看:37
本文介绍了如何在 Unity 方法中使用 UDP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 Cube 对象并附加了这个脚本.

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

我想使用UDP来控制立方体的移动,所以我创建了UDPManager.

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.

收到udp命令后可以调用unity方法吗?

Can I call unity methods when I receive udp command?

推荐答案

你不能从另一个线程调用 Unity API.如何在 Unity 中使用线程:

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

1.开始线程

2.在那个新线程中处理输入

2. Process Input in that new thread

3.告诉 Unity 您已完成处理.您可以通过将全局 boolean 变量设置为 true 来实现此目的.将输出数据存储在另一个全局变量中.

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.检查 Update() 函数中的 boolean 变量是否发生了变化.如果确实如此,请将其设置为 false.处理输出...

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

同时将 udp = new UdpClient(12345);Start 函数移动到 ThreadMethod 函数.

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

这篇关于如何在 Unity 方法中使用 UDP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆