如何使Unity中的c与Python通信

2024-04-27 05:18:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个Unity游戏制作一个Q-Learning机器人,这个机器人是用Python编写的,游戏是用c#编写的,如何让这两个程序交换任何类型的数据(即整数字符串数组等)? 任何让Python和c#for Unity通信的方法都能解决我的问题, 我可以将任何东西集成到我的代码中。在

编辑:另一个问题和我的一样,但答案并没有解释从Python方面应该做什么。在

我的Python版本是3.6。在


Tags: 数据方法字符串答案代码程序游戏编辑
2条回答

我假设机器人和游戏是分开的,可能是远程进程。对于双向通信,您可以考虑使用一些消息传递中间件或web服务。在

我怀疑更大的问题是事情的统一性。Unity拥有自己的网络API,就像大多数专有平台一样。我不确定在Unity中使用独立的基于http或tcp的服务有多复杂。在

Unity文档中的This page介绍了与非统一应用程序的集成。如果你想走web服务的道路,webhook将是你的最佳选择。在

RabbitMQ显然有一个Unity3d client,您可能可以找到其他类似的开源项目。在

这是我用来在unity和python之间进行通信的。来自不同来源/教程的混合。在

(它对我有用,但一个已知的问题是,当python中出现错误时,Unity就会冻结。我已经编写了一个try/catch方法,它返回一个空的bytearray,但似乎不起作用。)

C脚本

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

    /// <summary>
    /// Helper function for sending and receiving.
    /// </summary>
    /// <param name="dataOut">Data to send</param>
    /// <returns></returns>
    protected float[] ServerRequest(float[] dataOut)
    {
        //print("request");
        this.dataOut = dataOut; //debugging
        this.dataIn = SendAndReceive(dataOut); //debugging
        return this.dataIn;
    }

    /// <summary> 
    /// Send data to port, receive data from port.
    /// </summary>
    /// <param name="dataOut">Data to send</param>
    /// <returns></returns>
    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代码

^{pr2}$

如果您想提出请求,让您的Unity脚本(您正在使用的脚本)从SocketFloat派生:

public class Turing : SocketFloat

调用ServerRequest返回Python的预测。在

float[] prediction = ServerRequest(myArray)

相关问题 更多 >