Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Change the Device Preset of the Device Simulator from an editor script?

Discussion in 'Editor & General Support' started by PeterMills, Mar 14, 2023.

  1. PeterMills

    PeterMills

    Joined:
    Jun 20, 2013
    Posts:
    7
    I'm trying to automate testing my adaptive UI resizing. I want to make a script that cycles through device presets, then changes the UI view, then cycles through the devices again.

    I can't find a way to access that functionality, or even the current device from the 'UnityEditor.DeviceSimulation' namespace.

    I think I might be missing some needed understanding about how to access editor windows? maybe?

    Or is it impossible because the needed methods are marked as internal in Device Simulator?

    Does anyone have any ideas on how I might proceed?
     
    DimasSup likes this.
  2. Taobao

    Taobao

    Joined:
    Oct 25, 2015
    Posts:
    9
    I found your question while was searching for the same answer. Since I wrote the solution, I will share it here.

    In our project I'm using Reflection to access DeviceSimulator internals and manipulate them. I wrote a class that allows you to quickly select most quirky and most common devices from hotbar in Scene View and also you can iterate through all of them. I'm pretty sure you'll find everything you need in my solution.
    "using Sirenix.Utilities" dependency is not required at all, you can delete it and ditch an Expand call, no worries, it's just for UI. I tested this code using 2021.3.27f1

    Here how it looks in Scene View:


    Code (CSharp):
    1. #if UNITY_EDITOR
    2. using System;
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. using System.Reflection;
    6. using Sirenix.Utilities;
    7. using UnityEditor;
    8. using UnityEngine;
    9.  
    10. namespace ACME.Tools.DeviceSimulatorHelper {
    11.     [InitializeOnLoad]
    12.     public sealed class DeviceSimulatorHelper {
    13.         private const float AreaWidth = 270f;
    14.         private const float AreaHeight = 20f;
    15.        
    16.         private static readonly List<SimulatorDeviceInHotBar> _deviceInHotBars = new() {
    17.             new() {
    18.                 FriendlyName = "Samsung Galaxy Z Fold2 5G (Phone)",
    19.                 DisplayInHotBarName = "Fold 1"
    20.             },
    21.             new() {
    22.                 FriendlyName = "Samsung Galaxy Z Fold2 5G (Tablet)",
    23.                 DisplayInHotBarName = "Fold 2"
    24.             },
    25.             new() {
    26.                 FriendlyName = "Apple iPhone 13 Pro Max",
    27.                 DisplayInHotBarName = "iPhone"
    28.             },
    29.             new() {
    30.                 FriendlyName = "Google Pixel 2 XL",
    31.                 DisplayInHotBarName = "16:9"
    32.             },
    33.         };
    34.         private static bool _isSimulatorDeviceIndexesWarmedUp;
    35.        
    36.         private static Lazy<Assembly> DeviceSimulatorAssembly => new(() => AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(assembly => assembly.GetName().Name == "UnityEditor.DeviceSimulatorModule"));
    37.         private static Lazy<Type> SimulatorWindowType => new(() => DeviceSimulatorAssembly.Value.GetType("UnityEditor.DeviceSimulation.SimulatorWindow"));
    38.         private static Lazy<FieldInfo> SimulatorWindowMainField => new(() => SimulatorWindowType.Value.GetField("m_Main", BindingFlags.Instance | BindingFlags.NonPublic));
    39.         private static Lazy<Type> DeviceSimulatorMainType => new(() => DeviceSimulatorAssembly.Value.GetType("UnityEditor.DeviceSimulation.DeviceSimulatorMain"));
    40.         private static Lazy<Type> DeviceInfoAssetType => new(() => DeviceSimulatorAssembly.Value.GetType("UnityEditor.DeviceSimulation.DeviceInfoAsset"));
    41.         private static Lazy<Type> DeviceInfoType => new(() => DeviceSimulatorAssembly.Value.GetType("UnityEditor.DeviceSimulation.DeviceInfo"));
    42.         private static Lazy<FieldInfo> DeviceSimulatorMainDeviceIndexField => new(() => DeviceSimulatorMainType.Value.GetField("m_DeviceIndex", BindingFlags.Instance | BindingFlags.NonPublic));
    43.         private static Lazy<PropertyInfo> DeviceSimulatorMainDeviceIndexProperty => new(() => DeviceSimulatorMainType.Value.GetProperty("deviceIndex", BindingFlags.Instance | BindingFlags.Public));
    44.         private static Lazy<FieldInfo> DeviceSimulatorMainDevicesField => new(() => DeviceSimulatorMainType.Value.GetField("m_Devices", BindingFlags.Instance | BindingFlags.NonPublic));
    45.  
    46.         private static Lazy<FieldInfo> DeviceInfoAssetDeviceInfoField => new(() => DeviceInfoAssetType.Value.GetField("deviceInfo", BindingFlags.Instance | BindingFlags.Public));
    47.         private static Lazy<FieldInfo> DeviceInfoFriendlyNameField => new(() => DeviceInfoType.Value.GetField("friendlyName", BindingFlags.Instance | BindingFlags.Public));
    48.  
    49.         private static Lazy<GUIStyle> SelectedButtonStyle => new(() => new GUIStyle(GUI.skin.button) {
    50.             normal = {
    51.                 textColor = new Color(0.49f, 0.81f, 0.5f),
    52.             },
    53.             hover = {
    54.                 textColor = new Color(0.55f, 0.87f, 0.56f),
    55.             },
    56.         });
    57.  
    58.         private static float _sceneWindowHeight;
    59.         private static Lazy<Type> GameViewType => new(() => {
    60.             var result = AppDomain.CurrentDomain.GetAssemblies()
    61.                 .SelectMany(assembly => assembly.GetTypes())
    62.                 .FirstOrDefault(type => type.Namespace == "UnityEditor" && type.Name == "PlayModeView");
    63.  
    64.             if (result == null) {
    65.                 throw new Exception("UnityEditor.PlayModeView does NOT exist in current version.");
    66.             }
    67.  
    68.             return result;
    69.         });
    70.        
    71.         private static EditorWindow _activeGameView;
    72.         private static EditorWindow ActiveGameView {
    73.             get {
    74.                 if (_activeGameView != null && _activeGameView.hasFocus) {
    75.                     return _activeGameView;
    76.                 }
    77.  
    78.                 var gameViews = Resources.FindObjectsOfTypeAll(GameViewType.Value);
    79.                 foreach (var gameView in gameViews) {
    80.                     var current = gameView as EditorWindow;
    81.                     if (current != null && current.hasFocus) {
    82.                         _activeGameView = current;
    83.                         return _activeGameView;
    84.                     }
    85.                 }
    86.  
    87.                 return null;
    88.             }
    89.         }
    90.  
    91.         static DeviceSimulatorHelper() {
    92.             SceneView.duringSceneGui += OnSceneGUI;
    93.         }
    94.  
    95.         private static void OnSceneGUI(SceneView sceneView) {
    96.             if (!IsInSimulatorState()) {
    97.                 return;
    98.             }
    99.  
    100.             WarmUpSimulatorDeviceIndexes();
    101.  
    102.             Handles.BeginGUI();
    103.            
    104.             EditorGUILayout.BeginVertical();
    105.             GUILayout.FlexibleSpace();
    106.             EditorGUILayout.EndVertical();
    107.             var scale = GUILayoutUtility.GetLastRect();
    108.             if (scale.height > 1f) {
    109.                 _sceneWindowHeight = scale.height;
    110.             }
    111.  
    112.             var drawAreaRect = new Rect(10f, _sceneWindowHeight - AreaHeight - 6f, AreaWidth, AreaHeight);
    113.             GUILayout.BeginArea(drawAreaRect);
    114.             GUILayout.BeginHorizontal();
    115.            
    116.             if (GUILayout.Button("<", GUILayout.Width(25))) {
    117.                 SelectPreviousSimulatorDevice();
    118.             }
    119.  
    120.             ForActiveDeviceSimulatorMain(deviceSimulatorMain => {
    121.                 foreach (var deviceInHotBar in _deviceInHotBars) {
    122.                     if (deviceInHotBar.Index == SimulatorDeviceInHotBar.InvalidIndex) {
    123.                         continue;
    124.                     }
    125.                     var isSelected = (int)DeviceSimulatorMainDeviceIndexField.Value.GetValue(deviceSimulatorMain) == deviceInHotBar.Index;
    126.                
    127.                     if (GUILayout.Button(deviceInHotBar.DisplayInHotBarName, isSelected ? SelectedButtonStyle.Value : GUI.skin.button, GUILayout.Width(50))) {
    128.                         SelectSimulatorDevice(deviceInHotBar.FriendlyName);
    129.                     }
    130.                 }
    131.             });
    132.  
    133.             if (GUILayout.Button(">", GUILayout.Width(25))) {
    134.                 SelectNextSimulatorDevice();
    135.             }
    136.  
    137.             GUILayout.EndHorizontal();
    138.             GUILayout.EndArea();
    139.             Handles.EndGUI();
    140.  
    141.             var currentEvent = Event.current;
    142.             if (currentEvent.type == EventType.ScrollWheel && drawAreaRect.Expand(15f).Contains(currentEvent.mousePosition)) {
    143.                 if (currentEvent.delta.y < 0) {
    144.                     SelectPreviousSimulatorDevice();
    145.                 }
    146.                 else {
    147.                     SelectNextSimulatorDevice();
    148.                 }
    149.                
    150.                 currentEvent.Use();
    151.             }
    152.         }
    153.  
    154.         private static void WarmUpSimulatorDeviceIndexes() {
    155.             if (_isSimulatorDeviceIndexesWarmedUp) {
    156.                 return;
    157.             }
    158.  
    159.             ForActiveDeviceSimulatorMain(deviceSimulatorMain => {
    160.                 var devices = DeviceSimulatorMainDevicesField.Value.GetValue(deviceSimulatorMain) as Array;
    161.                
    162.                 var index = 0;
    163.                 foreach (var device in devices) {
    164.                     var deviceInfo = DeviceInfoAssetDeviceInfoField.Value.GetValue(device);
    165.                     var friendlyName = DeviceInfoFriendlyNameField.Value.GetValue(deviceInfo).ToString();
    166.                     foreach (var deviceInHotBar in _deviceInHotBars) {
    167.                         if (deviceInHotBar.FriendlyName == friendlyName) {
    168.                             deviceInHotBar.Index = index;
    169.                         }
    170.                     }
    171.  
    172.                     ++index;
    173.                 }
    174.                
    175.                 _isSimulatorDeviceIndexesWarmedUp = true;
    176.             });
    177.         }
    178.  
    179.         private static void SelectNextSimulatorDevice() {
    180.             ForActiveDeviceSimulatorMain(deviceSimulatorMain => {
    181.                 var currentIndex = DeviceSimulatorMainDeviceIndexField.Value.GetValue(deviceSimulatorMain);
    182.                 var nextIndex = (int)currentIndex + 1;
    183.                 var devices = DeviceSimulatorMainDevicesField.Value.GetValue(deviceSimulatorMain) as Array;
    184.                
    185.                 if (nextIndex >= devices.Length) {
    186.                     nextIndex = 0;
    187.                 }
    188.  
    189.                 SelectSimulatorDevice(nextIndex);
    190.             });
    191.         }
    192.  
    193.         private static void SelectPreviousSimulatorDevice() {
    194.             ForActiveDeviceSimulatorMain(deviceSimulatorMain => {
    195.                 var currentIndex = DeviceSimulatorMainDeviceIndexField.Value.GetValue(deviceSimulatorMain);
    196.                 var prevIndex = (int)currentIndex - 1;
    197.                
    198.                 if (prevIndex < 0) {
    199.                     var devices = DeviceSimulatorMainDevicesField.Value.GetValue(deviceSimulatorMain) as Array;
    200.                     prevIndex = devices.Length - 1;
    201.                 }
    202.  
    203.                 SelectSimulatorDevice(prevIndex);
    204.             });
    205.         }
    206.  
    207.         private static void SelectSimulatorDevice(int index) {
    208.             ForActiveDeviceSimulatorMain(deviceSimulatorMain => {
    209.                 DeviceSimulatorMainDeviceIndexProperty.Value.SetValue(deviceSimulatorMain, index);
    210.             });
    211.         }
    212.  
    213.         private static void SelectSimulatorDevice(string deviceName) {
    214.             ForActiveDeviceSimulatorMain(deviceSimulatorMain => {
    215.                 var devices = DeviceSimulatorMainDevicesField.Value.GetValue(deviceSimulatorMain) as Array;
    216.  
    217.                 var index = 0;
    218.                 foreach (var device in devices) {
    219.                     var deviceInfo = DeviceInfoAssetDeviceInfoField.Value.GetValue(device);
    220.                     var friendlyName = DeviceInfoFriendlyNameField.Value.GetValue(deviceInfo).ToString();
    221.                     if (friendlyName == deviceName) {
    222.                         DeviceSimulatorMainDeviceIndexProperty.Value.SetValue(deviceSimulatorMain, index);
    223.                         return;
    224.                     }
    225.  
    226.                     ++index;
    227.                 }
    228.             });
    229.         }
    230.  
    231.         private static void ForActiveDeviceSimulatorMain(Action<object> callback) {
    232.             var simulatorWindow = Resources.FindObjectsOfTypeAll(SimulatorWindowType.Value).FirstOrDefault();
    233.             if (simulatorWindow == null) {
    234.                 return;
    235.             }
    236.  
    237.             var deviceSimulatorMain = SimulatorWindowMainField.Value.GetValue(simulatorWindow);
    238.             if (deviceSimulatorMain != null) {
    239.                 callback(deviceSimulatorMain);
    240.             }
    241.         }
    242.  
    243.         private static bool IsInSimulatorState() {
    244.             if (ActiveGameView == null) {
    245.                 return false;
    246.             }
    247.  
    248.             return ActiveGameView.titleContent.text == "Simulator";
    249.         }
    250.  
    251.         private class SimulatorDeviceInHotBar {
    252.             public const int InvalidIndex = -1;
    253.            
    254.             public string FriendlyName;
    255.             public string DisplayInHotBarName;
    256.  
    257.             public int Index = InvalidIndex;
    258.         }
    259.     }
    260. }
    261. #endif
     
  3. Cobo3

    Cobo3

    Joined:
    Jun 16, 2013
    Posts:
    66
    Unity actually supports adding "plugins" to the Device Simulator that show when you click on the Control Panel button.

    I adapted TaoBao's code as such.
    Note: I simplified it to my needs (It no longer needs to be Lazy, and I removed the shortcut device names).
    Code (CSharp):
    1. using System;
    2. using System.Reflection;
    3. using UnityEditor.DeviceSimulation;
    4. using UnityEngine;
    5. using UnityEngine.UIElements;
    6.  
    7. namespace ACME.Tools.DeviceSimulatorHelper
    8. {
    9.     public sealed class DeviceSwitcher : DeviceSimulatorPlugin
    10.     {
    11.         readonly FieldInfo _mainField;
    12.         readonly PropertyInfo _deviceIndexProperty;
    13.         readonly FieldInfo _devicesField;
    14.         readonly UnityEngine.Object _simulatorWindow;
    15.  
    16.         public override string title => "Device Switcher";
    17.  
    18.         public DeviceSwitcher()
    19.         {
    20.             var assembly = Assembly.GetAssembly(typeof(DeviceSimulator));
    21.             var windowType = assembly.GetType("UnityEditor.DeviceSimulation.SimulatorWindow");
    22.             _mainField = windowType.GetField("m_Main", BindingFlags.Instance | BindingFlags.NonPublic);
    23.             var mainType = assembly.GetType("UnityEditor.DeviceSimulation.DeviceSimulatorMain");
    24.             _deviceIndexProperty = mainType.GetProperty("deviceIndex", BindingFlags.Instance | BindingFlags.Public);
    25.             _devicesField = mainType.GetField("m_Devices", BindingFlags.Instance | BindingFlags.NonPublic);
    26.  
    27.             _simulatorWindow = Resources.FindObjectsOfTypeAll(windowType)[0];
    28.         }
    29.  
    30.         public override VisualElement OnCreateUI()
    31.         {
    32.             var root = new VisualElement();
    33.             root.style.flexDirection = FlexDirection.Row;
    34.  
    35.             var previousButton = new RepeatButton(SelectPreviousSimulatorDevice, 500, 250);
    36.             var nextButton = new RepeatButton(SelectNextSimulatorDevice, 500, 250);
    37.             previousButton.text = "Previous";
    38.             nextButton.text = "Next";
    39.             previousButton.AddToClassList("unity-button");
    40.             nextButton.AddToClassList("unity-button");
    41.  
    42.             root.Add(previousButton);
    43.             root.Add(nextButton);
    44.  
    45.             return root;
    46.         }
    47.  
    48.         private void SelectPreviousSimulatorDevice() => SelectDeviceWithOffset(-1);
    49.  
    50.         private void SelectNextSimulatorDevice() => SelectDeviceWithOffset(1);
    51.  
    52.         private void SelectDeviceWithOffset(int offset)
    53.         {
    54.             var main = _mainField.GetValue(_simulatorWindow);
    55.             var devices = _devicesField.GetValue(main) as Array;
    56.  
    57.             var index = (int)_deviceIndexProperty.GetValue(main);
    58.             index = (int)Mathf.Repeat(index + offset, devices!.Length);
    59.  
    60.             _deviceIndexProperty.SetValue(main, index);
    61.         }
    62.     }
    63. }
     
    Taobao likes this.