[英]How to start a process in Unity3D but not stuck Unity?
I'm trying to start a process to excute a shell script with C# in Unity3D on MacOS, and I write the code below.我正在尝试在 MacOS 上启动使用 Unity3D 中的 C# 执行 shell 脚本的过程,我在下面编写代码。
[MenuItem("Test/Shell")]
public static void TestShell()
{
Process proc = new Process();
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.WorkingDirectory = Application.dataPath;
proc.StartInfo.Arguments = "t.sh";
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
Debug.Log(e.Data);
}
});
proc.Start();
proc.BeginOutputReadLine();
proc.WaitForExit();
proc.Close();
}
Shell script:: Shell 脚本::
echo "1"
sleep 2s
open ./
echo "4"
When I run this code, Unity3D get stuck until the shell script excute complete.当我运行此代码时,Unity3D 会卡住,直到 shell 脚本执行完成。 I tried to uncommit "proc.WaitForExit();", it did open the finder and not stuck anymore, but output nothing.
我试图取消提交“proc.WaitForExit();”,它确实打开了查找器并且不再卡住,但是 output 什么也没有。
So how can I start a process in Unity3D and get the output of the shell script immediately?那么如何在 Unity3D 中启动一个进程并立即获取 shell 脚本的 output 呢?
As said simply run the entire thing in a separate thread:如前所述,只需在一个单独的线程中运行整个事情:
[MenuItem("Test/Shell")]
public static void TestShell()
{
var thread = new Thread(TestShellThread);
thread.Start();
}
private static void TestShellThread ()
{
Process proc = new Process();
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.WorkingDirectory = Application.dataPath;
proc.StartInfo.Arguments = "t.sh";
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
Debug.Log(e.Data);
}
});
proc.Start();
proc.BeginOutputReadLine();
proc.WaitForExit();
proc.Close();
}
Note though in general: If you want to use the result in any Unity API related things besides logging you will need to dispatch them back into the main thread!但请注意:如果您想在任何与 Unity API 相关的事情中使用结果,除了日志记录之外,您需要将它们分派回主线程!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.