您的位置:首页 > 运维架构 > Shell

Unity调用外部EXE或Shell命令

2015-12-23 10:03 597 查看
1、开门见山的需求

有的时候,我们想把一些外部命令集成到unity中,比如,你想通过点击Unity中的一个按钮,就更新SVN(假设该项目是受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);
{
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:\AA\BB\CC。那么你在命令行可以直接输入d.exe来调用他。

好了。关于命令行的就讲这么多啦~~进入第4步。

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了咯。

文章转载自Unity调用外部EXE或Shell命令,感谢原作者 “kakashi8841”提供好文章
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: