コガネブログ

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

【Unity】Device Simulator でデバイスが変更された時に呼び出されるイベント

ソースコード

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

namespace Kogane
{
    [InitializeOnLoad]
    public static class DeviceSimulatorDeviceChecker
    {
        private static readonly Type      SIMULATOR_WINDOW_TYPE       = typeof( SimulatorWindow );
        private static readonly FieldInfo DEVICE_SIMULATOR_MAIN_FIELD = SIMULATOR_WINDOW_TYPE.GetField( "m_Main", BindingFlags.Instance | BindingFlags.NonPublic );

        private static DeviceInfoAsset m_currentDevice;

        public static event Action OnChangeDevice;

        static DeviceSimulatorDeviceChecker()
        {
            EditorApplication.update += () => OnUpdate();
        }

        private static void OnUpdate()
        {
            if ( OnChangeDevice == null ) return;

            var simulatorWindow = Resources
                    .FindObjectsOfTypeAll<SimulatorWindow>()
                    .FirstOrDefault()
                ;

            if ( simulatorWindow == null ) return;

            var deviceSimulatorMain = ( DeviceSimulatorMain ) DEVICE_SIMULATOR_MAIN_FIELD.GetValue( simulatorWindow );
            var newDevice           = deviceSimulatorMain.currentDevice;

            if ( m_currentDevice != newDevice )
            {
                OnChangeDevice();
            }

            m_currentDevice = newDevice;
        }
    }
}

注意

Name が「UnityEditor.DeviceSimulation.Tests.Common」の
Assembly Definition を作成する必要があります