Unity 显示git分支
最近工作内容比较多,涉及多版本问题处理。但是git的地址是以工程名做的目录(也就是工程名改不了),导致本地同一个git地址的两个unity工程显示一模一样。导致改动的时候经常改错。就想着Unity显示所在的分支就好了。搜了下,网上是有类似的插件,例如GitHub for Unity,https://blog.csdn.net/gitblog_00027/article/details/143911382但是,我也不想因为我这小小的功能就去下一个开发工具包。只能用写代码了。经过deepseek的帮助和自我改动。结果还实现出来了。下面是具体的讲解。
获取git分支呢?
获取git分支,本质上是调用git命令。下面是具体的实现
private static void UpdateBranchMenu(){// 获取当前项目的根目录string projectRoot = Application.dataPath.Replace("/Assets", "");// 创建进程start信息ProcessStartInfo startInfo = new ProcessStartInfo();startInfo.FileName = "git"; // 执行的命令startInfo.Arguments = "branch --show-current"; // 命令参数:获取当前分支名startInfo.WorkingDirectory = projectRoot; // 设置工作目录为项目根目录startInfo.RedirectStandardOutput = true; // 重定向标准输出,以便我们读取startInfo.UseShellExecute = false; // 不使用操作系统shellstartInfo.CreateNoWindow = true; // 不创建新窗口// 启动进程Process process = new Process();process.StartInfo = startInfo;process.Start();// 读取命令输出(即分支名称)currentBranch = process.StandardOutput.ReadToEnd().Trim();// 等待进程结束process.WaitForExit();process.Close();}
分支显示到面板中
开始想这是显示到菜单栏里面。但是[MenuItem()]里面的参数不支持动态修改。因此废弃。最后显示到了场景里面。下面是具体的显示效果。

Scene面板显示显示自定义UI
这涉及编辑器代码,不多说直接贴出来
SceneView.duringSceneGui += OnSceneGUI;
private static void OnSceneGUI(SceneView sceneView){if (overlayStyle == null){// 使用 GUI.skin 中的安全样式if (GUI.skin != null && GUI.skin.button != null){overlayStyle = new GUIStyle(GUI.skin.button);overlayStyle.normal.textColor = Color.white;overlayStyle.alignment = TextAnchor.MiddleCenter;overlayStyle.fontSize = 10;}else{// 备用方案:完全自定义overlayStyle = new GUIStyle();overlayStyle.normal.textColor = Color.white;overlayStyle.alignment = TextAnchor.MiddleCenter;overlayStyle.fontSize = 10;overlayStyle.padding = new RectOffset(6, 6, 3, 3);}}Handles.BeginGUI();if (overlayStyle == null){return;}// 在Scene视图右上角显示分支信息float width = 120;float height = 20;float x = sceneView.position.width - width - 10;float y = 10;Rect branchRect = new Rect(x, y, width, height);// 背景框EditorGUI.DrawRect(branchRect, new Color(0.1f, 0.1f, 0.1f, 0.9f));// 分支文本GUI.Label(branchRect, $"🌿 {currentBranch}", overlayStyle);Handles.EndGUI();}
实时更新
最后且分支的,或者改代码的时候需要监听其状态通过注册EditorApplication类的focusChanged事件和delayCall来实现。另外记得在所在类上标记[InitializeOnLoad]属性用于初始化
static GitBranchOverlay(){EditorApplication.focusChanged +=OnFocusCalled;EditorApplication.delayCall += UpdateBranchMenu;//EditorApplication.update += UpdateBranchInfo;SceneView.duringSceneGui += OnSceneGUI;}
参考链接
https://blog.csdn.net/gitblog_00027/article/details/143911382
