I want to execute Python processing → C # processing in Unity
If you want to run a chat system written in Python with Unity, a process called Process in C # is required. However, if you do heavy processing synchronously in Process, Unity will freeze! When asynchronous processing is performed in Process, C # processing cannot be executed after Python processing!
//Variable to save the output data
private StringBuilder output = new StringBuilder();
public void Python()
{
//Launch a new process
var p = new Process();
//Process settings
p.StartInfo.FileName = pyExePath; //Python file location
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.Arguments = pyCodePath; //File name to execute
p.StartInfo.StandardOutputEncoding = Encoding.GetEncoding("shift_jis"); //Shift the output result of Python-Convert to jis
//Event handler settings
//Called every time there is output from python
p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
string str = e.Data;
if (!String.IsNullOrEmpty(str))
{
UnityEngine.Debug.Log(str);
output.Append(str+"\n");
}
});
p.Start();
UnityEngine.Debug.Log("Started asynchronously during process execution");
}
void Update()
{
if(output.Length != 0){
UnityEngine.Debug.Log("Runs after the process is complete");
output.Length = 0 ;
}
}
}
If you write the following process in the function that performs Process, it will not work, so by taking the method of executing it with the Update function when the output result from Python obtained by Process is obtained, it was possible to make Python → C #.
Recommended Posts