Hi!
I know that you guys are already tired of these questions, but could you please have a look at my code.
I’m trying to update the Transform component of the object using the data from the server. According to the log, the data is received, however it can not be applied. I’ve been trying to move transform to the other places, unfortunately without success.
There are no compilation errors, but whenever I press play, the object receives data once,
Trying to receive data...
UnityEngine.Debug:Log(Object)
Received Data-0.812725159675, 0.582647247338, 0.0
UnityEngine.Debug:Log(Object)
and then gives the following error.
get_transform can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
UnityEngine.Component:get_transform()
PlayerBehavior:receiveData() (at Assets/Scripts/PlayerBehavior.cs:44)
PlayerBehavior:<Start>m__0() (at Assets/Scripts/PlayerBehavior.cs:22)
Here is the code:
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class PlayerBehavior : MonoBehaviour {
private UdpClient udpServer;
public GameObject cube;
private Vector3 tempPos;
private Thread t;
public float movementSpeed;
private long lastSend;
private IPEndPoint remoteEP;
void Start()
{
udpServer = new UdpClient(1234);
t = new Thread(() => {
while (true) {
this.receiveData();
}
});
t.Start();
t.IsBackground = true;
remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 41234);
}
private void OnApplicationQuit()
{
udpServer.Close();
t.Abort();
}
private void receiveData() {
Debug.Log("Trying to receive data...");
byte[] data = udpServer.Receive(ref remoteEP);
if (data.Length > 0)
{
var str = System.Text.Encoding.Default.GetString(data);
Debug.Log("Received Data" + str);
string[] messageParts = str.Split(',');
transform.position = new Vector3(
float.Parse(messageParts[0]),
float.Parse(messageParts[1]),
float.Parse(messageParts[2])
);
}
}
}
Thanks a lot in advance!