从Unity运行Python脚本,以便在我的游戏中使用其输出(文本文件)



我正在尝试从Unity(C#脚本)运行Python脚本来使用其输出,这是我游戏中的文本文件,事实是,当我运行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:UsersHPAppDataLocalProgramsPythonPython36-32python.exe";
        pythonInfo.Arguments=@"C:UsersHPDocumentsprojet1.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和哪个版本),您可以尝试直接运行Python在使用Ironpython的代码中,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.htmlhttps://forum.unity.com/threads/ironpython-in-unity-a-good-idea.225544/

  • 使用链接Unity Python 0.4.1
  • 下载Unity Python软件包
  • 然后,转到编辑>项目设置>播放器>其他设置>配置和更改脚本运行时版本为"实验(.net 4.6等效)。

假设您有一个小的代码片段。

class Test():
    def __init__(self, name):
        self.name = name
    def display(self):
        return "Hi, " + self.name

您可以从c#使用

使用它
using System.Collections;
using System.Collections.Generic;
using IronPython.Hosting;
using UnityEngine;
public class PythonInterfacer : MonoBehaviour {
 void Start () {
        var engine = Python.CreateEngine();
        ICollection<string> searchPaths = engine.GetSearchPaths();
        //Path to the folder of greeter.py
        searchPaths.Add(@"C:UsersCodemakerDocumentsPythonDemoAssetsScriptsPython");
        //Path to the Python standard library
        searchPaths.Add(@"C:UsersCodemakerDocumentsPythonDemoAssetsPluginsLib");
        engine.SetSearchPaths(searchPaths);
        dynamic py = engine.ExecuteFile(@"C:UsersCodemakerDocumentsPythonDemoAssetsScriptsPythontest.py");
        dynamic obj = py.Test("Codemaker");
        Debug.Log(obj.display());
    }
}

这是我的工作。希望这会有所帮助。

var psi = new ProcessStartInfo();
// point to python virtual env
psi.FileName = @"C:UserssomeoneDocumentsgit-reposPythonVenvsvenvScriptspython.exe";
// Provide arguments
var script = @"AssetsScriptssomecoolpythonstuffcool.py";
var vidFileIn = "111";
var inputPath = @"Assetsinput";
var outputPath = @"Assetsoutput";
psi.Arguments = string.Format(""{0}" -v "{1}" -i "{2}" -o "{3}"", 
                               script, vidFileIn, inputPath, outputPath);
// Process configuration
psi.UseShellExecute = false;
psi.CreateNoWindow = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
// Execute process and get output
var errors = "nothing";
var results = "nothing";
using (var process = Process.Start(psi))
{
    errors = process.StandardError.ReadToEnd();
    results = process.StandardOutput.ReadToEnd();
}
// grab errors and display them in UI
StringBuilder buffy = new StringBuilder();
buffy.Append("ERRORS:n");
buffy.Append(errors);
buffy.Append("nn");
buffy.Append("Results:n");
buffy.Append(results);
// ui text object
responseText.Text = buffy.ToString();

您可以尝试以下GitHub存储库代码。您将获得一个从文件中使用python代码的基本想法

Unity Python Demo

最新更新