#unity/代码缓存 #unity/日常积累
unity 命令行,执行多行指令:先跳转到c盘根目录,创建git_backup文件夹,通过git clone,拉取https://192.168.0.223:8843/igengine/cgbu_sdk.git到本地
using UnityEngine;
using System.Diagnostics;
public class GitCloneExample : MonoBehaviour
{
void Start()
{
ExecuteGitCommands();
}
void ExecuteGitCommands()
{
// 多条命令使用 && 连接
string commands = "cd C:\\ && mkdir git_backup && cd git_backup && git clone https://192.168.0.223:8843/igengine/cgbu_sdk.git";
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c " + commands;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
// 获取输出
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
// 打印输出
UnityEngine.Debug.Log("Output:\n" + output);
if (!string.IsNullOrEmpty(error))
{
UnityEngine.Debug.LogError("Error:\n" + error);
}
}
}
代码解释
多行命令的组合:我们用 && 将每个命令连在一起,这样每条命令都会依次执行。只有当前命令成功后,才会继续执行下一条命令。
string commands = "cd C:\\ && mkdir git_backup && cd git_backup && git clone https://192.168.0.223:8843/igengine/cgbu_sdk.git";
启动进程:将 cmd.exe 的参数设置为 "/c " + commands,从而让 cmd 执行多条命令并在完成后自动关闭。
重定向输出:通过 RedirectStandardOutput 和 RedirectStandardError 捕获命令的输出和错误,并在 Unity 控制台中显示。
git,且能通过命令行直接调用。这个代码示例在 Unity 编辑器内执行会触发指定命令,且在控制台中显示克隆进度和任何错误信息。
如果你想执行 PowerShell 命令,只需将 cmd.exe 替换为 powershell.exe: