我有一个代码来检查我的 WebGL 应用程序中的设备是否是移动设备。我想改进这段代码来检测手机是 iOS 还是 Android。我该怎么做?
插件.jslib
var MyPlugin = {
IsMobile: function()
{
return UnityLoader.SystemInfo.mobile;
}
};
mergeInto(LibraryManager.library, MyPlugin);
团结:
[DllImport("__Internal")]
private static extern bool IsMobile();
public bool isMobile()
{
#if !UNITY_EDITOR && UNITY_WEBGL
return IsMobile();
#endif
return false;
}
基于这个回应 看来你可以做类似的事情:
var MyPlugin = {
IsMobile: function()
{
return UnityLoader.SystemInfo.mobile;
},
IsIOSPlatform : function()
{
var userAgent = navigator.userAgent;
isIOS = (
/\b(iPhone)\b/i.test(userAgent) ||
/\b(iPad|iPod)\b/i.test(userAgent) ||
// iPad on iOS 13 detection
(userAgent.includes("Mac") && "ontouchend" in document)
);
return isIOS;
},
IsAndroidPlatform : function()
{
var userAgent = navigator.userAgent;
isAndroid = (
/\b(Android)\b/i.test(userAgent)
);
return isAndroid;
}
};
@LoïcLeGrosFrère 的答案很有效,但需要支持,并且正则表达式评估有额外的开销。
Unity引擎已经确定了操作系统系列,代码可以是这样的:
团结:
[DllImport("__Internal")]
private static extern bool isAndroid();
[DllImport("__Internal")]
private static extern bool isIos();
[DllImport("__Internal")]
private static extern string getOperationSystemFamilyName();
[DllImport("__Internal")]
private static extern void freeBuffer(string ptr);
public bool IsAndroid()
{
#if !UNITY_EDITOR && UNITY_WEBGL
return isAndroid()
#else
return false;
#endif
}
public bool IsIos()
{
#if !UNITY_EDITOR && UNITY_WEBGL
return isIos()
#else
return false;
#endif
}
public string GetOperationSystemFamilyName()
{
#if !UNITY_EDITOR && UNITY_WEBGL
var os = getOperationSystemFamilyName();
var copy = String.Copy(os);
freeBuffer(os);
return copy;
#else
return SystemInfo.operatingSystem;
#endif
}
js:
mergeInto(LibraryManager.library, {
isAndroid : function() {
return Module.SystemInfo.os === "Android";
},
isIos : function() {
return Module.SystemInfo.os === "iPhoneOS" || Module.SystemInfo.os === "iPadOS" || Module.SystemInfo.os === "macOS";
},
getOperationSystemFamilyName: function() {
var os = Module.SystemInfo.os;
var bufferSize = lengthBytesUTF8(os) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(os, buffer, bufferSize);
return buffer;
},
freeBuffer: function(ptr) {
_free(ptr);
}
});
malloc 和 free 非常昂贵。最好的方法是分配一次缓冲区,例如在启动时,并在应用程序结束时释放它。