Skip to content

Instantly share code, notes, and snippets.

@dj-kusuha
Last active February 27, 2024 13:06
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dj-kusuha/a24e17a2d13e37e71214 to your computer and use it in GitHub Desktop.
Save dj-kusuha/a24e17a2d13e37e71214 to your computer and use it in GitHub Desktop.
Unityエディタ上からGameビューのスクリーンショットを撮るEditor拡張。
using UnityEditor;
using UnityEngine;
namespace djkusuha.Utility
{
/// <summary>
/// Unityエディタ上からGameビューのスクリーンショットを撮るEditor拡張
/// </summary>
public class CaptureScreenshotFromEditor : Editor
{
/// <summary>
/// キャプチャを撮る
/// </summary>
/// <remarks>
/// Edit > CaptureScreenshot に追加。
/// HotKeyは Ctrl + Shift + F12。
/// </remarks>
[MenuItem("Edit/CaptureScreenshot #%F12")]
private static void CaptureScreenshot()
{
// 現在時刻からファイル名を決定
var filename = System.DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".png";
// キャプチャを撮る
#if UNITY_2017_1_OR_NEWER
ScreenCapture.CaptureScreenshot(filename); // ← GameViewにフォーカスがない場合、この時点では撮られない
#else
Application.CaptureScreenshot(filename); // ← GameViewにフォーカスがない場合、この時点では撮られない
#endif
// GameViewを取得してくる
var assembly = typeof(EditorWindow).Assembly;
var type = assembly.GetType("UnityEditor.GameView");
var gameview = EditorWindow.GetWindow(type);
// GameViewを再描画
gameview.Repaint();
Debug.Log("ScreenShot: " + filename);
}
}
}
@dj-kusuha
Copy link
Author

Application.CaptureScreenshot の時点では、Gameビューにフォーカスが無いとキャプチャしたファイルが保存されないようだったので、スクリプトからGameビューを取得・再描画をさせています。
これによってどのタイミングで呼ばれてもファイルが保存されます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment