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
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值