Unity调用外部EXE或Shell命令

2015年08月10日 14:43 0 点赞 0 评论 更新于 2025-11-21 15:57

作者:卡卡西0旗木 原文:http://www.taidous.com/forum.php?mod=viewthread&tid=27979

1. 需求概述

在某些场景下,我们希望将一些外部命令集成到Unity项目中。例如,当项目受SVN管理时,我们想通过点击Unity中的一个按钮来更新SVN。这就涉及到Unity调用外部可执行文件、bat/shell脚本等操作。这种需求较为常见,并且实现起来并不困难。

2. 实现方法

我们先封装一个用于调用命令的函数:

private static void processCommand(string command, string argument)
{
ProcessStartInfo start = new ProcessStartInfo(command);
start.Arguments = argument;
start.CreateNoWindow = false;
start.ErrorDialog = true;
start.UseShellExecute = true;

if (start.UseShellExecute)
{
start.RedirectStandardOutput = false;
start.RedirectStandardError = false;
start.RedirectStandardInput = false;
}
else
{
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
start.RedirectStandardInput = true;
start.StandardOutputEncoding = System.Text.UTF8Encoding.UTF8;
start.StandardErrorEncoding = System.Text.UTF8Encoding.UTF8;
}

Process p = Process.Start(start);

if (!start.UseShellExecute)
{
printOutPut(p.StandardOutput);
printOutPut(p.StandardError);
}

p.WaitForExit();
p.Close();
}

如果大家对上述代码相关的内容感兴趣,可以自行去MSDN查询API。若不关心这些,可继续往下看该函数的使用方法。

3. 命令行基础教学

上面封装的函数中,第一个参数是命令名,第二个参数是该命令接受的参数。对于没有接触过命令行的同学,下面我们一起感受一下命令行操作;如果对命令行比较熟悉的同学,可以直接跳到第4步。以下操作基于WIN7系统:

  • 步骤A:按下Win + R组合键,在弹出的运行窗口中输入“cmd”,然后回车。
  • 步骤B:此时会弹出一个命令行窗口。
  • 步骤C:在命令行窗口中输入命令“notepad”,然后回车。
  • 步骤D:这时会发现记事本程序被打开了。
  • 步骤E:假设D盘有一个名为1.txt的文件。
  • 步骤F:在命令行中输入“notepad D:\1.txt”,然后回车,即可使用记事本直接打开D盘的1.txt文件。

简单来说,上述示例中的“notepad”就是我们要传入封装函数的第一个参数,而“D:\1.txt”则是第二个参数。

那么,可执行的命令有哪些呢?系统变量PATH中所有路径下的exe、bat/bash(Linux)文件都可以执行。你可以通过在命令行中输入“echo %PATH%”来获取PATH的信息,也可以通过“桌面” -> “计算机” -> 右键选择“属性” -> “高级系统设置”,在“环境变量”中查看PATH。双击PATH变量可以进行查看和编辑。如果某个路径不在PATH中,要调用该路径下的exe文件就只能使用全路径了。例如,若想调用D:\AA\BB\CC\d.exe这个exe文件,而PATH中没有D:\AA\BB\CC路径,那么在命令行中每次都要输入D:\AA\BB\CC\d.exe来调用它;若PATH中有该路径,则在命令行中可以直接输入d.exe来调用。

4. 调用封装函数

例如,我们现在想更新SVN,只需在Unity中合适的位置(比如创建一个脚本)执行以下代码:

public class SvnForUnity
{
static string SVN_BASE = "F:\\Project\\Game";

[MenuItem("SVN/Update", false, 1)]
public static void SvnUpdate()
{
processCommand("svn", "update \"" + SVN_BASE + "\"");
}

private static void processCommand(string command, string argument)
{
ProcessStartInfo start = new ProcessStartInfo(command);
start.Arguments = argument;
start.CreateNoWindow = false;
start.ErrorDialog = true;
start.UseShellExecute = true;

if (start.UseShellExecute)
{
start.RedirectStandardOutput = false;
start.RedirectStandardError = false;
start.RedirectStandardInput = false;
}
else
{
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
start.RedirectStandardInput = true;
start.StandardOutputEncoding = System.Text.UTF8Encoding.UTF8;
start.StandardErrorEncoding = System.Text.UTF8Encoding.UTF8;
}

Process p = Process.Start(start);

if (!start.UseShellExecute)
{
printOutPut(p.StandardOutput);
printOutPut(p.StandardError);
}

p.WaitForExit();
p.Close();
}
}

执行上述代码后,Unity中会出现“SVN/Update”按钮,点击该按钮即可更新SVN。

作者信息

洞悉

洞悉

共发布了 3994 篇文章