WebGL: 与浏览器脚本交互

作者:追风剑情 发布于:2022-6-16 15:24 分类:Unity3d

[官网] WebGL:与浏览器脚本交互

创建*.jslib库文件

创建*.jslib文件并存放到Assets/Plugins目录下。

示例: WebJS.jslib

mergeInto(LibraryManager.library, {
	// 获取浏览器运行平台信息
	GetUserAgent : function() {
		var str = navigator.userAgent;
		var bufferSize = lengthBytesUTF8(str) + 1;
		var buffer = _malloc(bufferSize);
		stringToUTF8(str, buffer, bufferSize);
		return buffer;
	},
});  

封装C#层接口

using UnityEngine;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
/// <summary>
/// 对应*.jslib接口
/// </summary>
public class WebJS : MonoBehaviour
{
    //获取浏览器运行平台信息
    //如:
    //Mozilla/5.0 (Windows NT 10.0; Win64; x64)
    //AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36
    [DllImport("__Internal")]
    public static extern string GetUserAgent();

    //判断浏览器是否运行在移动平台上
    public static bool IsMobilePlatform
    {
        get
        {
            if (Application.platform == RuntimePlatform.WindowsEditor)
                return false;
            string userAgent = GetUserAgent();
            Regex regex = new Regex(@"iPhone|iPad|iPod|Android");
            return regex.IsMatch(userAgent);
        }
    }
}  

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号