1+ // **************************************************************** //
2+ //
3+ // Copyright (c) RimuruDev. All rights reserved.
4+ // Contact me:
5+ // - Gmail: rimuru.dev@gmail.com
6+ // - LinkedIn: https://www.linkedin.com/in/rimuru/
7+ // - GitHub: https://github.com/RimuruDev
8+ //
9+ // **************************************************************** //
10+
11+ using System ;
12+ using UnityEngine ;
13+
14+ #if UNITY_EDITOR
15+ using UnityEditor ;
16+ using UnityEditor . DeviceSimulation ;
17+ #endif
18+
19+ namespace RimuruDev
20+ {
21+ [ Flags ]
22+ [ Serializable ]
23+ public enum CurrentDeviceType : byte
24+ {
25+ WebPC = 0 ,
26+ WebMobile = 2 ,
27+ }
28+
29+ [ SelectionBase ]
30+ [ DisallowMultipleComponent ]
31+ [ DefaultExecutionOrder ( - 100 ) ]
32+ [ HelpURL ( "https://github.com/RimuruDev/Unity-WEBGL-DeviceTypeDetector" ) ]
33+ public sealed class DeviceTypeDetector : MonoBehaviour
34+ {
35+ [ field: SerializeField ] public CurrentDeviceType CurrentDeviceType { get ; private set ; }
36+
37+ #if UNITY_2020_1_OR_NEWER
38+ [ SerializeField ] private bool enableDeviceSimulator = true ;
39+ #endif
40+ private void Awake ( )
41+ {
42+ if ( IsMobile ( ) && enableDeviceSimulator )
43+ {
44+ Debug . Log ( "WEBGL -> Mobile" ) ;
45+ CurrentDeviceType = CurrentDeviceType . WebMobile ;
46+ }
47+ else
48+ {
49+ Debug . Log ( "WEBGL -> PC" ) ;
50+ CurrentDeviceType = CurrentDeviceType . WebPC ;
51+ }
52+ }
53+
54+ #if UNITY_EDITOR
55+ public static bool IsMobile ( )
56+ {
57+ #if UNITY_2020_1_OR_NEWER
58+ if ( DeviceSimulatorExists ( ) && IsDeviceSimulationActive ( ) )
59+ return true ;
60+ #endif
61+ return false ;
62+ }
63+
64+ private static bool DeviceSimulatorExists ( )
65+ {
66+ var simulatorType = typeof ( Editor ) . Assembly . GetType ( "UnityEditor.DeviceSimulation.DeviceSimulator" ) ;
67+ return simulatorType != null ;
68+ }
69+
70+ private static bool IsDeviceSimulationActive ( )
71+ {
72+ var simulatorType = typeof ( Editor ) . Assembly . GetType ( "UnityEditor.DeviceSimulation.DeviceSimulator" ) ;
73+ if ( simulatorType != null )
74+ {
75+ var simulatorInstance = simulatorType . GetProperty ( "instance" , System . Reflection . BindingFlags . Static | System . Reflection . BindingFlags . Public ) ? . GetValue ( null ) ;
76+ var isDeviceActive = simulatorType . GetProperty ( "isDeviceActive" , System . Reflection . BindingFlags . NonPublic | System . Reflection . BindingFlags . Instance ) ? . GetValue ( simulatorInstance ) ;
77+ return ( bool ) isDeviceActive ;
78+ }
79+ return false ;
80+ }
81+ #else
82+ [ System . Runtime . InteropServices . DllImport ( "__Internal" ) ]
83+ public static extern bool IsMobile ( ) ;
84+ #endif
85+ }
86+ }
0 commit comments