文章目录

前言1.python部分2.unity部分

总结

前言

unity调用python代码后,想把python生成的数据内容直接传到unity内的ui面板上,但不是通过socket通信传递数据。这里直接捕获python内print到控制台的内容。

1.python部分

python代码部分直接print输出想要传递的数据

2.unity部分

传递的数据通过文本的方式被unity接收,通过字符串操作获取想要的数据

public class gtPrediction : MonoBehaviour

{

private ProcessStartInfo startInfo;

private Process process;

private static StringBuilder output = new StringBuilder();

void Start()

{

Kill_All_Python_Process();

// 创建UDP通信的Client

udpClient = new UdpClient();

// 设置IP地址与端口号

remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 31412);

localEP = new IPEndPoint(IPAddress.Any, 0);

//string pythonPath = Application.dataPath + "/TDSTF/TDSTF-main/main.py";

string pythonPath = "D:/main.py";

// 创建Process

process = new Process();

// 创建ProcessStartInfo对象

startInfo = new ProcessStartInfo();

process.StartInfo = startInfo;

// 设定执行cmd

//startInfo.FileName = @"E:/DTprediction/Library/PythonInstall/python.exe";

startInfo.FileName = Application.dataPath + "/StreamingAssets/PythonInstall/python.exe";

// 输入参数是上一步的command字符串

startInfo.Arguments = pythonPath;

// 因为嵌入Unity中后台使用,所以设置不显示窗口

startInfo.CreateNoWindow = true;

// 这里需要设定为false

startInfo.UseShellExecute = false;

startInfo.RedirectStandardInput = true; //打开流输入

// 设置重定向这个进程的标准输出流,用于直接被Unity C#捕获,从而实现 Python -> Unity 的通信

startInfo.RedirectStandardOutput = true;

// 设置重定向这个进程的标准报错流,用于在Unity的C#中进行Debug Python里的bug

startInfo.RedirectStandardError = true;

//process.StandardInput.AutoFlush = true;//每次调用 Write()之后,将其缓冲区刷新到基础流

process.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived);

process.ErrorDataReceived += new DataReceivedEventHandler(OnErrorDataReceived);

//启动脚本Process,并且激活逐行读取输出与报错

process.Start();

process.BeginErrorReadLine();

process.BeginOutputReadLine();

}

private void OnOutputDataReceived(object sender, DataReceivedEventArgs e)

{

if (!string.IsNullOrEmpty(e.Data))

{

output.Append(e.Data);

UnityEngine.Debug.Log(output.ToString());

}

}

private void OnErrorDataReceived(object sender, DataReceivedEventArgs e)

{

if (!string.IsNullOrEmpty(e.Data))

{

// 调试语句

UnityEngine.Debug.LogError("Received error output: " + e.Data);

}

}

}

总结

output.ToString()就是想要的数据了,直接显示在ui即可。

相关阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: