gpt4 book ai didi

c# - 从 unity 运行一个 python 脚本,稍后在我的游戏中使用它的输出(文本文件)

转载 作者:太空狗 更新时间:2023-10-29 21:45:12 26 4
gpt4 key购买 nike

我正在尝试从 unity(C# 脚本)运行一个 python 脚本以使用它的输出,这是我稍后在游戏中的文本文件,问题是当我在 unity 中运行 C# 脚本时没有任何反应(Python 脚本有效自己就好)。谁能告诉我我错过了什么?谢谢。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.IO;
using UnityEngine.UI;
using System.Text.RegularExpressions;
using System.Diagnostics;

using System.Runtime.InteropServices;
public class PyCx : MonoBehaviour {
public Text Message;
public GameObject OpenPanel1 = null;
// Use this for initialization
void Start () {
python ();
read ();
ShowMessage ();
}
public void python(){
ProcessStartInfo pythonInfo = new ProcessStartInfo ();
Process python;
pythonInfo.FileName=@"C:\Users\HP\AppData\Local\Programs\Python\Python36-32\python.exe";
pythonInfo.Arguments=@"C:\Users\HP\Documents\projet1.pyw";
pythonInfo.CreateNoWindow = false;
pythonInfo.UseShellExecute = false;
python = Process.Start (pythonInfo);
python.WaitForExit ();
python.Close ();
}
public void read(){
using (var reader = new StreamReader ("C://Users//HP//Documents//result.txt")) {
string line = reader.ReadToEnd ();
Message.text = (line);
}
}
public void ShowMessage(){
OpenPanel1.SetActive (true);
Message.IsActive ();
}
// Update is called once per frame
void Update () {

}
}

最佳答案

与其使用在受控开发环境之外可能不可靠的进程(您甚至不知道您的用户是否安装了 Python 以及哪个版本),您可以尝试使用 IronPython 在您的代码中直接运行 Python,IronPython 是一个用于 CLR 的 Python 解释器,因此它甚至不需要安装 Python 来执行您的脚本。

要使用它,您需要从 http://ironpython.net/download/ 下载已编译的二进制文件

然后将所有需要的程序集复制到您的资源文件夹中:

  • IronPython.dll
  • IronPython.Modules.dll
  • Microsoft.Scripting.Core.dll
  • Microsoft.Scripting.dll
  • Microsoft.Scripting.Debugging.dll
  • Microsoft.Scripting.ExtensionAttribute.dll
  • Microsoft.Dynamic.dll

然后您将可以访问 Python 引擎,您可以按如下方式对其进行初始化:

PythonEngine engine = new PythonEngine();  
engine.LoadAssembly(Assembly.GetAssembly(typeof(GameObject)));
engine.ExecuteFile("Project1.py");

您可以在此处查看更多信息:http://ironpython.net/documentation/

引用资料

http://shrigsoc.blogspot.com.es/2016/07/ironpython-and-unity.html https://forum.unity.com/threads/ironpython-in-unity-a-good-idea.225544/

关于c# - 从 unity 运行一个 python 脚本,稍后在我的游戏中使用它的输出(文本文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47855380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com