【问题标题】:How to start a process in Unity3D but not stuck Unity?如何在 Unity3D 中启动一个进程但不卡住 Unity?
【发布时间】:2022-01-23 13:15:41
【问题描述】:

我正在尝试在 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 脚本::

echo "1"
sleep 2s
open ./
echo "4"

当我运行此代码时,Unity3D 会卡住,直到 shell 脚本执行完成。 我尝试取消提交“proc.WaitForExit();”,它确实打开了查找器并且不再卡住,但什么也没输出。

那么如何在 Unity3D 中启动一个进程并立即获得 shell 脚本的输出呢?

【问题讨论】:

  • 我不知道,但我会尝试在另一个线程中运行该进程以检查它是否有效

标签: c# unity3d


【解决方案1】:

如前所述,只需在单独的线程中运行整个事情:

[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 相关的事情中使用结果,您需要将它们分派回主线程!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多