【Unity3d】在Unity3d中调用外部程序及批处理文件,写自动化编译脚本需要注意的地方

如果调用外部普通应用程序, 比如notepad.exe 这样调用

static public bool ExecuteProgram(string exeFilename, string workDir, string args)
{
	System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
	info.FileName = exeFilename;
	info.WorkingDirectory = workDir;
	info.RedirectStandardOutput = true;
	info.RedirectStandardError = true;
	info.Arguments = args;
	info.UseShellExecute = false;
	info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

	System.Diagnostics.Process task = null;

	bool rt = true;

	try
	{
		task = System.Diagnostics.Process.Start(info);
		if (task != null)
		{
			task.WaitForExit(10000);
		} 
		else
		{
			return false;
		}
	} 
	catch (Exception e)
	{
		Debug.LogError("Error: " + e.ToString());
		return false;
	} 
	finally
	{
		if (task != null && task.HasExited)
		{
			string output = task.StandardError.ReadToEnd();
			if (output.Length > 0)
			{
				Debug.LogError(output);
			}
			
			output = task.StandardOutput.ReadToEnd();
			if (output.Length > 0)
			{
				Debug.Log("Error: " + output);
			}
			
			rt = (task.ExitCode == 0);
		}
	}

	return rt;
}


如果需要调用Window的批处理文件BAT, 

或者含有控制台输出的程序, 

或者使用上面的方法卡死, 则使用下面的方法运行

static bool ExecuteProgram(string exeFilename, string workDir, string args)
{
	System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
	info.FileName = exeFilename;
	info.WorkingDirectory = workDir;
	info.UseShellExecute = true;
	info.Arguments = args;
	info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

	System.Diagnostics.Process task = null;
	bool rt = true;
	try
	{
		Debug.Log("ExecuteProgram:" + args);
		
		task = System.Diagnostics.Process.Start(info);
		if (task != null)
		{
			task.WaitForExit(100000);
		}
		else
		{
			return false;
		}
	}
	catch (Exception e)
	{
		Debug.LogError("ExecuteProgram:" + e.ToString());
		return false;
	} 
	finally
	{
		if (task != null && task.HasExited)
		{
			rt = (task.ExitCode == 0);
		}
	}

	return rt;
}



你可能感兴趣的:(Unity3d,游戏开发)