我正在嘗試在 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();
}
外殼腳本::
echo "1"
sleep 2s
open ./
echo "4"
當我運行此代碼時,Unity3D 會卡住,直到 shell 腳本執行完成。我試圖取消提交“proc.WaitForExit();”,它確實打開了查找器,不再卡住,但什么也沒輸出。
那么如何在 Unity3D 中啟動一個行程并立即獲得 shell 腳本的輸出呢?
uj5u.com熱心網友回復:
如前所述,只需在單獨的執行緒中運行整個事情:
[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();
}
但一般請注意:如果您想在除日志記錄之外的任何 Unity API 相關事物中使用結果,您將需要將它們分派回主執行緒!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/389973.html
上一篇:使用webapi更新多條記錄
