Skip to content

Instantly share code, notes, and snippets.

@chiepomme
Created June 15, 2022 00:51
Show Gist options
  • Save chiepomme/937d3f3997bb4ff3207b011a01181b25 to your computer and use it in GitHub Desktop.
Save chiepomme/937d3f3997bb4ff3207b011a01181b25 to your computer and use it in GitHub Desktop.
Take a screen shot on a Unity Device Simulator window.
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEditor.DeviceSimulation;
using UnityEngine;
using UnityEngine.UIElements;
public class TakeScreenShotPlugin : DeviceSimulatorPlugin
{
public override string title => "Screen Shot";
Button takeScreenShotButton;
public override VisualElement OnCreateUI()
{
var root = new VisualElement();
takeScreenShotButton = new Button { text = "Take Screen Shot" };
takeScreenShotButton.clicked += () =>
{
var simulatorWindowType = AppDomain
.CurrentDomain
.GetAssemblies()
.SelectMany(asm => asm.GetTypes())
.Single(x => x.FullName == "UnityEditor.DeviceSimulation.SimulatorWindow");
// UnityEditor.DeviceSimulation.SimulatorWindow
var simulatorWindow = typeof(EditorWindow)
.GetMethod(nameof(EditorWindow.GetWindow), 1, new Type[0])
.MakeGenericMethod(simulatorWindowType)
.Invoke(null, new object[0]);
// UnityEditor.DeviceSimulation.DeviceSimulatorMain
var simulatorMain = simulatorWindow
.GetType()
.GetField("m_Main", BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(simulatorWindow);
// UnityEditor.DeviceSimulation.DeviceInfoAsset
var currentDeviceAsset = simulatorMain
.GetType()
.GetProperty("currentDevice")
.GetValue(simulatorMain);
// UnityEditor.DeviceSimulation.DeviceInfo
var currentDeviceInfo = currentDeviceAsset
.GetType()
.GetField("deviceInfo")
.GetValue(currentDeviceAsset);
var friendlyName = (string)currentDeviceInfo
.GetType()
.GetField("friendlyName")
.GetValue(currentDeviceInfo);
var dir = new DirectoryInfo("ScreenShots");
if (!dir.Exists) dir.Create();
var path = Path.Combine(dir.FullName, $"{friendlyName}.png");
ScreenCapture.CaptureScreenshot(path);
Debug.Log($"A screen shot was saved to {path}");
};
root.Add(takeScreenShotButton);
return root;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment