工作中经常会遇到需要截图给项目经理或者设计人员的需求。平时用惯了微信就会顺手用Alt+A进行截图了,但是在Unity编辑器中Game窗口最大化也不会铺满全屏,我们也无法截取到满意的尺寸。Unity Package Manager中提供了一个插件“Recoder”,这个插件功能强大可以截图、录制GIF和录制视频,我不想每次都安装这个插件于是就自己做一个简易的截图工具,把这个工具附加在框架中,这样可以很方便的进行调用了。
在scripts文件夹中新建一个“Editor”文件夹,然后在‘Editor’文件中新建一个‘ScreenCaptureEditor’脚本。粘贴下面的代码,等编译完成后从工具栏可以打开截图工具了。
using System.IO; using UnityEditor; using UnityEngine; public class ScreenCaptureEditor : EditorWindow { private static string directory = "Screenshots/Capture/"; private static string latestScreenshotPath = ""; private bool initDone = false; private GUIStyle BigText; void InitStyles() { initDone = true; BigText = new GUIStyle(GUI.skin.label) { fontSize = 20, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter, normal = new GUIStyleState() { textColor=Color.green} }; } private void OnGUI() { if (!initDone) { InitStyles(); } GUILayout.Label("游戏窗口截图", BigText); if (GUILayout.Button("截图")) { TakeScreenshot(1); } GUILayout.Label("分辨率: " + GetResolution(1)); if (GUILayout.Button("双倍分辨率截图")) { TakeScreenshot(2); } GUILayout.Label("分辨率: " + GetResolution(2)); if (GUILayout.Button("打开目录")) { ShowFolder(); } GUILayout.Label("保存目录: " + directory); } [MenuItem("Tools/截图")] public static void ShowWindow() { var window = GetWindowWithRect<ScreenCaptureEditor>(new Rect(0, 0, 180, 250)); window.titleContent = new GUIContent("截图工具"); window.Focus(); window.Repaint(); } private static void ShowFolder() { if (File.Exists(latestScreenshotPath)) { EditorUtility.RevealInFinder(latestScreenshotPath); return; } Directory.CreateDirectory(directory); EditorUtility.RevealInFinder(directory); } private static void TakeScreenshot(int super) { Directory.CreateDirectory(directory); var currentTime = System.DateTime.Now; var filename = currentTime.ToString().Replace('/', '-').Replace(':', '_') + ".png"; var path = directory + filename; ScreenCapture.CaptureScreenshot(path,super); latestScreenshotPath = path; Debug.Log($"Screenshot saved: <b>{path}</b> with resolution <b>{GetResolution(super)}</b>"); } private static string GetResolution(int super) { Vector2 size = UnityEditor.Handles.GetMainGameViewSize(); Vector2Int sizeInt = new Vector2Int((int)size.x, (int)size.y); return $"{sizeInt.x*super}x{sizeInt.y*super}"; } }