Unity WebGL构建中如何区分Mac与Windows操作系统?
在Unity WebGL中区分Mac/Windows操作系统的方法
Unity的Application.platform在WebGL构建下只会返回WebGLPlayer,没法直接区分Mac和Windows,这时候得借助浏览器的JavaScript API来获取系统信息,再传递给Unity的C#代码。下面是具体实现步骤:
1. 编写WebGL JavaScript插件
在Unity项目中创建Plugins/WebGL目录(如果没有的话),新建一个名为SystemDetection.jslib的文件,内容如下:
mergeInto(LibraryManager.library, { GetOSPlatform: function() { const userAgent = navigator.userAgent; const isMac = /Mac/.test(userAgent); const isWindows = /Win/.test(userAgent); if (isMac) { return Pointer_stringify("MacOS"); } else if (isWindows) { return Pointer_stringify("Windows"); } else { return Pointer_stringify("Unknown"); } } });
这个脚本通过浏览器的navigator.userAgent字符串判断当前系统,然后返回对应的标识。
2. 编写C#调用代码
创建一个静态类来封装调用逻辑,同时兼容非WebGL环境:
using UnityEngine; using System.Runtime.InteropServices; public static class SystemDetector { [DllImport("__Internal")] private static extern string GetOSPlatform(); public static string GetCurrentOS() { #if UNITY_WEBGL && !UNITY_EDITOR // WebGL构建环境下调用JS方法 return GetOSPlatform(); #else // 编辑器或其他平台直接用Application.platform判断 switch (Application.platform) { case RuntimePlatform.WindowsPlayer: case RuntimePlatform.WindowsEditor: return "Windows"; case RuntimePlatform.OSXPlayer: case RuntimePlatform.OSXEditor: return "MacOS"; default: return "Unknown"; } #endif } }
3. 在业务代码中使用
需要适配键盘提示等内容时,直接调用这个工具类:
void UpdateKeyboardHints() { string currentOS = SystemDetector.GetCurrentOS(); if (currentOS == "MacOS") { // 切换到Mac风格的键盘提示,比如显示Command键图标 keyHintImage.sprite = macCommandSprite; } else if (currentOS == "Windows") { // 切换到Windows风格的键盘提示,比如显示Ctrl键图标 keyHintImage.sprite = windowsCtrlSprite; } }
注意事项
- 确保JS文件放在
Plugins/WebGL目录下,Unity会自动将其纳入WebGL构建包 - 编辑器中测试时会走非WebGL分支,要验证WebGL环境的效果需要构建后在浏览器中运行
navigator.userAgent的判断逻辑覆盖了绝大多数主流场景,特殊设备可能需要微调正则表达式
内容的提问来源于stack exchange,提问作者Brian Boddaert
相关产品推荐
相关产品推荐

