在 webgl 中检测移动客户端

Detect mobile client in webgl

我需要检测用户是否是 运行 移动浏览器或 desktop/laptop 浏览器中的 webgl 应用程序。是否可以使用 Unity API 进行检测,或者您需要进行一些 HTML hack?

我认为你在追求 preprocessor directives。它们发生在将您的代码编译为 pre-select 根据您正在构建的平台需要 运行 的代码之前。这就是为什么它们也被称为条件编译指令。

例如:

#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

要在浏览器中检测您的应用 运行 正在使用的设备,您需要使用 Navigator.userAgent 还要检查 windowNavigator

您还可以查看为您执行此操作的库,例如 this

对此有一个“技巧”。你可以通过 JavaScript 找到,所以你只需要 plugin connection between the c# and JavaScript e.g. using the Navigator.userAgent 有点像

var HandleIO = {
    IsMobilePlatform : function()
    {
        var userAgent = navigator.userAgent;
        isMobile = (
                    /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(userAgent) ||
                    /\b(Android|Windows Phone|iPad|iPod)\b/i.test(userAgent) ||
                    // iPad on iOS 13 detection
                    (userAgent.includes("Mac") && "ontouchend" in document)
                );
        return isMobile;
    }
};
mergeInto(LibraryManager.library, HandleIO);

把这个例如在像 Assets/WebGL/Plugins 这样的文件夹中,确保只为 WebGL

编译它

然后在 c# 端,您可以包含例如

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
}

所以稍后你就打电话给

var isMobile = WebGLBrowserCheck.IsMobileBrowser();

当然有更多的手机,OS然后是列出的手机,所以如果需要你可能想扩展它,但这些应该涵盖最常见的手机