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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…