Hi guys,
I’ve been trying to update my player’s position and rotation with the values received via UDP socket. The data comes without any difficulties, however the final step of assigning the received values to the Vector3 is problematic for me. I’m poorly experienced in C#, that’s why all the errors appear because of incorrect syntaxes. Could somebody please fix my code. Thanks a lot in advance.
I won’t post the whole code here, since it’s working and the data is received. Here is the final step of the data application. Please, tell me if the whole code is needed.
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(',');
Vector3.transform.position = new Vector3(
messageParts[0],
messageParts[1],
messageParts[2]
);
Vector3 transform.rotation = new Vector3(
messageParts[3],
messageParts[4],
messageParts[5]
);
}
}
EDIT The issue is solved now, thanks to @Hellium
Here is the final working script (must be cleaned though). The object receives the coordinates and updates Transform component properly.
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;
private float[] transformPosition = new float[3] ;
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);
}
void Update()
{
transform.position = new Vector3(transformPosition[0], transformPosition[1], transformPosition[2]) ;
}
private void OnApplicationQuit()
{
udpServer.Close();
t.Abort();
}
private void receiveData() {
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(',');
transformPosition[0] = float.Parse(messageParts[0]) ;
transformPosition[1] = float.Parse(messageParts[1]) ;
transformPosition[2] = float.Parse(messageParts[2]) ;
}
}
}