Python和unity通信的代码
时间: 2023-03-31 07:03:40 浏览: 154
你可以使用 Python 的 socket 模块和 Unity 的网络 API 进行通信。具体实现可以参考以下代码:
Python 代码:
```
import socket
HOST = '127...1' # Unity 的 IP 地址
PORT = 5005 # Unity 的端口号
# 创建 socket 对象
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接 Unity
s.connect((HOST, PORT))
# 发送消息给 Unity
s.sendall(b'Hello, Unity!')
# 接收来自 Unity 的消息
data = s.recv(1024)
# 关闭连接
s.close()
print('Received', repr(data))
```
Unity 代码:
```csharp
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SocketClient : MonoBehaviour
{
private const int PORT = 5005; // Python 的端口号
private const string HOST = "127...1"; // Python 的 IP 地址
private Socket clientSocket;
void Start()
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(new IPEndPoint(IPAddress.Parse(HOST), PORT));
}
void Update()
{
if (clientSocket.Poll(, SelectMode.SelectRead))
{
byte[] data = new byte[1024];
int count = clientSocket.Receive(data);
string message = Encoding.UTF8.GetString(data, , count);
Debug.Log(message);
}
}
void OnDestroy()
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
```
阅读全文