Home > Mobile >  Detect mobile client in webgl
Detect mobile client in webgl

Time:05-02

I need to detect whether the user is running a webgl app in a mobile browser or on a desktop/laptop browser. Is this possible to detect using the Unity API, or you need to do some HTML hack?

CodePudding user response:

There is a "hack" for this. You can find out via JavaScript so you just need a enter image description here

and then on the c# side you could include like e.g.

using System;
#if UNITY_WEBGL
using System.Runtime.InteropServices;
#endif
using UnityEngine;

public class WebGLBrowserCheck : MonoBehaviour
{
#if UNITY_WEBGL
    [DllImport("__Internal")]
    static extern bool IsMobilePlatform();

    public static bool IsMobileBrowser()
    {
#if UNITY_EDITOR
        return false; // value to return in Play Mode (in the editor)
#elif UNITY_WEBGL
        return IsMobilePlatform(); // value based on the current browser
#else
        return false;
#endif
    }
#endif
}

so later on you just call

var isMobile = WebGLBrowserCheck.IsMobileBrowser();

Of course there are more mobile phones and OS then the listed ones so you might want to extend it if needed but these should cover the most common ones

CodePudding user response:

In assets/plugins/webgl/MyPlugin.jslib The "WebGL" folder is one you can create yourself.

var MyPlugin = {
     IsMobile: function()
     {
         return UnityLoader.SystemInfo.mobile;
     }
 };

Then from unity:

 mergeInto(LibraryManager.library, MyPlugin);

     [DllImport("__Internal")]
     private static extern bool IsMobile();
 
     public bool isMobile()
     {
         #if !UNITY_EDITOR && UNITY_WEBGL
             return IsMobile();
         #endif
         return false;
     }

or you can use this to Check Application.platform.

if (Application.platform == RuntimePlatform.WindowsPlayer)
    Debug.Log("Do something special here");
else if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
    Debug.Log("Do something else here");

CodePudding user response:

I think you are after preprocessor directives. They take place before compiling your code to pre-select the code that needs to be run according the platform you are working building on. Thats why they're also called conditional compilation directives.

For example:

#if UNITY_EDITOR || UNITY_WEBGL
 //this code will be compiled and run while in editor or webgl build target in the build settings
#endif

#if UNITY_ANDROID 
 //this code will be compiled and run when the build target is set to android in the build settings
#endif

To detect which device your app is running in in the browser you need to use the Navigator.userAgent Check also the windowNavigator

You can check out also libraries that do that for you, such as this

  • Related