Unity发布webgl获取浏览器的URL
Unity发布webgl之后获取浏览器的url
在unity中创建文件夹Plugins,然后添加添加文件UnityGetBrowserURL.jslib
var GetUrlFunc = {
// 获取地址栏的URL(当前页面URL)
GetCurrentUrl: function () {
var returnStr = window.location.href;
var title = decodeURI(returnStr);
var bufferSize = lengthBytesUTF8(title) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(title, buffer, bufferSize);
return buffer;
},
// 获取浏览器顶部的URL(顶级窗口URL)
GetTopUrl: function () {
var returnStr = window.top.location.href;
var title = decodeURI(returnStr);
var bufferSize = lengthBytesUTF8(title) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(title, buffer, bufferSize);
return buffer;
}
};
mergeInto(LibraryManager.library, GetUrlFunc);
在Unity中添加代码
using UnityEngine;
using System.Runtime.InteropServices;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour
{
// 导入 JavaScript 方法
[DllImport("__Internal")]
private static extern string GetCurrentUrl(); // 获取当前页面的 URL
[DllImport("__Internal")]
private static extern string GetTopUrl(); // 获取顶级窗口的 URL
public string currentUrl = ""; // 当前页面的 URL
public string topUrl = ""; // 顶级窗口的 URL
public Button btnGetCurrentUrl; // 获取当前页面 URL 的按钮
public Button btnGetTopUrl; // 获取顶级窗口 URL 的按钮
public Text txtCurrentUrl; // 显示当前页面 URL 的文本框
public Text txtTopUrl; // 显示顶级窗口 URL 的文本框
private void Start()
{
// 初始化时获取 URL
GetCurrentURL();
GetTopURL();
// 为按钮添加点击事件
btnGetCurrentUrl.onClick.AddListener(() =>
{
GetCurrentURL();
});
btnGetTopUrl.onClick.AddListener(() =>
{
GetTopURL();
});
}
// 获取当前页面的 URL
private void GetCurrentURL()
{
#if UNITY_WEBGL && !UNITY_EDITOR
currentUrl = GetCurrentUrl();
txtCurrentUrl.text = currentUrl;
Debug.Log("Current URL: " + currentUrl);
#else
txtCurrentUrl.text = "Not running in WebGL";
Debug.Log("Not running in WebGL");
#endif
}
// 获取顶级窗口的 URL
private void GetTopURL()
{
#if UNITY_WEBGL && !UNITY_EDITOR
topUrl = GetTopUrl();
txtTopUrl.text = topUrl;
Debug.Log("Top URL: " + topUrl);
#else
txtTopUrl.text = "Not running in WebGL";
Debug.Log("Not running in WebGL");
#endif
}
/// <summary>
/// 如果URL中有参数可以进行参数的解释,
/// </summary>
/// <param name="queryString">查询字符串</param>
/// <returns>键值对字典key是参数key,value是参数值</returns>
public Dictionary<string, string> ParseQueryString(string queryString)
{
Dictionary<string, string> result = new Dictionary<string, string>();
// 使用正则表达式匹配键值对
string pattern = @"([^&=]+)=([^&]*)";
MatchCollection matches = Regex.Matches(queryString, pattern);
foreach (Match match in matches)
{
string key = Uri.UnescapeDataString(match.Groups[1].Value); // 解码键
string value = Uri.UnescapeDataString(match.Groups[2].Value); // 解码值
result[key] = value;
}
return result;
}
}
场景布局

发布webgl

拷贝到nginx

运行结果

在地址栏输入Ip:端口号/?serligblsdhroivbaelirbgvkersab ,/?后面是随便打的字符,然后按下enter会刷新网页并重新显示URL,(显示的文字和在编辑器下显示的文字不一致的原因是:webgl不支持unity自带的字体中的中文,换个其他的字体就行了)

Enjoy
资源可以私信获取,有不明白的欢迎私信留言
8万+

被折叠的 条评论
为什么被折叠?



