I am trying to control multiple objects in unity with position data comming from python. The position data is read as a csv filein python and then send to unity. The data is being send when I am not mistaken, but unity is not doing anything. Does anyone know why?
Python send code
import socket
import time
host, port = "127.0.0.1", 25001
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Allow reuse of the port
sock.connect((host, port))
startPos1 = [0, 0, 0] # Initial position for Cylinder1
startPos2 = [0, 0, 0] # Initial position for Cylinder2
try:
while True:
time.sleep(0.5) # Sleep 0.5 sec
# Update positions
startPos1[0] += 0.1 # Increase x by 0.1 for Cylinder1
startPos2[1] += 0.1 # Increase y by 0.1 for Cylinder2
# Convert positions to string format expected by Unity
posString1 = '(' + ','.join(map(str, startPos1)) + ')'
posString2 = '(' + ','.join(map(str, startPos2)) + ')'
posString = f"pos1:{posString1};pos2:{posString2}"
print(posString)
# Send position string to Unity
sock.sendall(posString.encode("UTF-8"))
# Receive and print the response from Unity
receivedData = sock.recv(1024).decode("UTF-8")
print(receivedData)
finally:
sock.close() # Ensure the socket is closed when done
Unity receiving code
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
using System.Threading;
public class CSharpForGIT : MonoBehaviour
{
Thread mThread;
public string connectionIP = "127.0.0.1";
public int connectionPort = 25001;
IPAddress localAdd;
TcpListener listener;
TcpClient client;
public GameObject cylinder1;
public GameObject cylinder2;
Vector3 receivedPos1 = Vector3.zero;
Vector3 receivedPos2 = Vector3.zero;
bool running;
private void Update()
{
transform.position = receivedPos; //assigning receivedPos in SendAndReceiveData()
cylinder1.transform.position = receivedPos1;
cylinder2.transform.position = receivedPos2;
}
private void Start()
{
ThreadStart ts = new ThreadStart(GetInfo);
mThread = new Thread(ts);
mThread.Start();
}
void GetInfo()
{
localAdd = IPAddress.Parse(connectionIP);
listener = new TcpListener(IPAddress.Any, connectionPort);
listener.Start();
client = listener.AcceptTcpClient();
running = true;
while (running)
{
SendAndReceiveData();
}
listener.Stop();
}
void SendAndReceiveData()
{
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---receiving Data from the Host----
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize); //Getting data in Bytes from Python
string dataReceived = Encoding.UTF8.GetString(buffer, 0, bytesRead); //Converting byte data to string
if (dataReceived != null)
{
//---Using received data---
receivedPos = StringToVector3(dataReceived); //<-- assigning receivedPos value from Python
print("received pos data, and moved the Cube!");
//---Sending Data to Host----
byte[] myWriteBuffer = Encoding.ASCII.GetBytes("Hey I got your message Python! Do You see this massage?"); //Converting string to byte data
nwStream.Write(myWriteBuffer, 0, myWriteBuffer.Length); //Sending the data in Bytes to Python
}
}
public static Vector3 StringToVector3(string sVector)
{
// Remove the parentheses
if (sVector.StartsWith("(") && sVector.EndsWith(")"))
{
sVector = sVector.Substring(1, sVector.Length - 2);
}
// split the items
string[] sArray = sVector.Split(',');
// store as a Vector3
Vector3 result = new Vector3(
float.Parse(sArray[0]),
float.Parse(sArray[1]),
float.Parse(sArray[2]));
return result;
}
/*
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new System.Exception("No network adapters with an IPv4 address in the system!");
}
*/
}
I tried changing the host number because unity gives an error: SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted.
I feel like with one object its working fine, but i want one script that controls 14 objects, based on an ID later on. So doesnt make sense to split everything in 14 scripts.
Vintertid is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.