Python отправляет код
Код: Выделить всё
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
Код: Выделить всё
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;
private object lockObject = new object();
bool running;
private void Update()
{
lock (lockObject)
{
if (cylinder1 != null)
{
cylinder1.transform.position = receivedPos1;
}
if (cylinder2 != null)
{
cylinder2.transform.position = receivedPos2;
}
}
}
private void Start()
{
ThreadStart ts = new ThreadStart(GetInfo);
mThread = new Thread(ts);
mThread.Start();
}
private void OnApplicationQuit()
{
running = false;
if (client != null) client.Close();
if (listener != null) listener.Stop();
if (mThread != null) mThread.Abort();
}
void GetInfo()
{
try
{
localAdd = IPAddress.Parse(connectionIP);
listener = new TcpListener(IPAddress.Any, connectionPort);
listener.Start();
client = listener.AcceptTcpClient();
running = true;
while (running)
{
SendAndReceiveData();
}
}
catch (SocketException ex)
{
Debug.Log("Socket exception: " + ex.ToString());
}
finally
{
listener.Stop();
}
}
void SendAndReceiveData()
{
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
string dataReceived = Encoding.UTF8.GetString(buffer, 0, bytesRead);
if (!string.IsNullOrEmpty(dataReceived))
{
ProcessReceivedData(dataReceived);
byte[] myWriteBuffer = Encoding.ASCII.GetBytes("Hey I got your message Python! Do You see this message?");
nwStream.Write(myWriteBuffer, 0, myWriteBuffer.Length);
}
}
void ProcessReceivedData(string data)
{
string[] positions = data.Split(';');
lock (lockObject)
{
foreach (var pos in positions)
{
if (pos.StartsWith("pos1:"))
{
receivedPos1 = StringToVector3(pos.Substring(5));
}
else if (pos.StartsWith("pos2:"))
{
receivedPos2 = StringToVector3(pos.Substring(5));
}
}
}
}
public static Vector3 StringToVector3(string sVector)
{
if (sVector.StartsWith("(") && sVector.EndsWith(")"))
{
sVector = sVector.Substring(1, sVector.Length - 2);
}
string[] sArray = sVector.Split(',');
Vector3 result = new Vector3(
float.Parse(sArray[0]),
float.Parse(sArray[1]),
float.Parse(sArray[2]));
return result;
}
}
Мне кажется, что с одним объектом все работает нормально, но мне нужен один скрипт, который позже будет управлять 14 объектами на основе идентификатора. Так что нет смысла разбивать все на 14 скриптов.
Подробнее здесь: https://stackoverflow.com/questions/785 ... munication