unity与python的通信_如何使Unity中的C#与Python通信

I'm making a Q-Learning bot for a Unity game, the bot is in Python and the game is in c#, how can I make the two programs exchange data of any kind (i.e integers string arrays etc)?

Any way to make Python and c# for Unity communicate will solve my problem,

I have no problem with integrating anything to my code.

Edit: The other question is like mine, but the answer doesn't explain what to do from the Python side.

My Python version is 3.6.

解决方案

This is what I use for communication between unity and python. A mix from different sources/tutorials.

(It works for me, but a known problem is that Unity freezes when there is an error in python. I already wrote a try/catch method that returns an empty bytearray, but that doesn't seem to work.)

C# script

using UnityEngine;

//using System.Net;

using System.Net.Sockets;

using System;

public class SocketFloat : MonoBehaviour

{

public string ip = "127.0.0.1";

public int port = 60000;

private Socket client;

[SerializeField]

private float[] dataOut, dataIn; //debugging

///

/// Helper function for sending and receiving.

///

/// Data to send

///

protected float[] ServerRequest(float[] dataOut)

{

//print("request");

this.dataOut = dataOut; //debugging

this.dataIn = SendAndReceive(dataOut); //debugging

return this.dataIn;

}

///

/// Send data to port, receive data from port.

///

/// Data to send

///

private float[] SendAndReceive(float[] dataOut)

{

//initialize socket

float[] floatsReceived;

client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

client.Connect(ip, port);

if (!client.Connected) {

Debug.LogError("Connection Failed");

return null;

}

//convert floats to bytes, send to port

var byteArray = new byte[dataOut.Length * 4];

Buffer.BlockCopy(dataOut, 0, byteArray, 0, byteArray.Length);

client.Send(byteArray);

//allocate and receive bytes

byte[] bytes = new byte[4000];

int idxUsedBytes = client.Receive(bytes);

//print(idxUsedBytes + " new bytes received.");

//convert bytes to floats

floatsReceived = new float[idxUsedBytes/4];

Buffer.BlockCopy(bytes, 0, floatsReceived, 0, idxUsedBytes);

client.Close();

return floatsReceived;

}

}

Python code

import socket

import struct

import traceback

import logging

import time

def sending_and_reciveing():

s = socket.socket()

socket.setdefaulttimeout(None)

print('socket created ')

port = 60000

s.bind(('127.0.0.1', port)) #local host

s.listen(30) #listening for connection for 30 sec?

print('socket listensing ... ')

while True:

try:

c, addr = s.accept() #when port connected

bytes_received = c.recv(4000) #received bytes

array_received = np.frombuffer(bytes_received, dtype=np.float32) #converting into float array

nn_output = return_prediction(array_received) #NN prediction (e.g. model.predict())

bytes_to_send = struct.pack('%sf' % len(nn_output), *nn_output) #converting float to byte

c.sendall(bytes_to_send) #sending back

c.close()

except Exception as e:

logging.error(traceback.format_exc())

print("error")

c.sendall(bytearray([]))

c.close()

break

sending_and_reciveing()

If you want to make a request, let your Unity script (the one you are working with) derive from SocketFloat:

public class Turing : SocketFloat

Calling ServerRequest returns a predictions from Python.

float[] prediction = ServerRequest(myArray)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Unity使用Python进行TCP通信,可以通过以下步骤实现: 1. 编写Python脚本实现TCP服务器或客户端功能。 2. 在Unity项目添加Python脚本,并使用Python.NET库将Python脚本导入到Unity。 3. 在Unity调用Python脚本,实现TCP通信功能。 下面是一个简单的示例,演示了如何在Unity使用Python实现TCP客户端通信: 1. 编写Python脚本 ``` import socket TCP_IP = '127.0.0.1' TCP_PORT = 5005 BUFFER_SIZE = 1024 MESSAGE = "Hello, World!" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) s.send(MESSAGE.encode()) data = s.recv(BUFFER_SIZE) s.close() print("received data:", data.decode()) ``` 这个脚本会连接到一个指定的IP地址和端口,发送一条消息并接收回复。 2. 导入Python脚本到UnityUnity项目,需要使用Python.NET库将Python脚本导入到C#脚本。可以从NuGet包管理器安装Python.NET,也可以手动下载并添加到项目。 在C#脚本,可以使用以下代码导入Python脚本: ``` using System; using Python.Runtime; public class PythonClient : MonoBehaviour { void Start() { // Initialize Python runtime PythonEngine.Initialize(); // Import Python script using (Py.GIL()) { dynamic client = Py.Import("tcp_client"); client.main(); } // Shutdown Python runtime PythonEngine.Shutdown(); } } ``` 这个脚本会初始化Python运行时,导入Python脚本并调用其的`main`函数。 3. 在Unity调用Python脚本 在需要使用TCP通信的地方,可以使用以下代码调用Python脚本: ``` using System; using Python.Runtime; public class MyComponent : MonoBehaviour { void Start() { using (Py.GIL()) { dynamic client = Py.Import("tcp_client"); client.main(); } } } ``` 这个脚本会在Unity调用Python脚本的`main`函数,实现TCP通信功能。 需要注意的是,在Unity使用Python进行TCP通信时,需要确保Python脚本和Unity项目使用的Python版本一致,否则可能会出现错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值