コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】DeviceSimulator のイベントを取得する例

ソースコード

using System.Reflection;
using UnityEditor;
using UnityEditor.DeviceSimulation;
using UnityEngine;

[InitializeOnLoad]
public static class Example
{
    static Example()
    {
        // 1 フレーム遅らせないと deviceSimulatorMain が null になる
        EditorApplication.delayCall += () =>
        {
            var simulatorWindowType      = typeof( SimulatorWindow );
            var simulatorWindow          = EditorWindow.GetWindow( simulatorWindowType );
            var deviceSimulatorMainField = simulatorWindowType.GetField( "m_Main", BindingFlags.Instance | BindingFlags.NonPublic );
            var deviceSimulatorMain      = ( DeviceSimulatorMain ) deviceSimulatorMainField.GetValue( simulatorWindow );
            var screenSimulation         = deviceSimulatorMain.ScreenSimulation;

            screenSimulation.OnOrientationChanged         += () => Debug.Log( "OnOrientationChanged" );
            screenSimulation.OnAllowedOrientationChanged  += () => Debug.Log( "OnAllowedOrientationChanged" );
            screenSimulation.OnResolutionChanged          += ( currentWidth, currentHeight ) => Debug.Log( $"OnResolutionChanged: {currentWidth}, {currentHeight}" );
            screenSimulation.OnFullScreenChanged          += isFullScreen => Debug.Log( $"OnFullScreenChanged: {isFullScreen}" );
            screenSimulation.OnInsetsChanged              += inset => Debug.Log( $"OnInsetsChanged: {inset}" );
            screenSimulation.OnScreenSpaceSafeAreaChanged += screenSpaceSafeArea => Debug.Log( $"OnScreenSpaceSafeAreaChanged: {screenSpaceSafeArea}" );
        };
    }
}

注意

上記のサイト様を参考に UnityEditor.DeviceSimulation.Tests.Common という名前の
AssemblyDefinitionFile を作成して DeviceSimulator の internal な API に
アクセスできるようにする必要がある