Unity读取发布WebGL,读取网页Cookie
版本:Unity2019
·1、新建GetCookie脚本,挂载到场景GetCookie(新建1个空物体修改名称)物体上
using System;
using UnityEngine;
public class GetCookie : MonoBehaviour
{
private void Start()
{
//存cookie
Application.ExternalCall("setCookie", "Cookietest", transform.position.x);
//读cookie
Application.ExternalCall("getCookie", "Cookietest");
}
//接受方法
public void ReciveCookieMsg(string str)
{
Debug.Log("读取的Cookie:" + str);
}
}
2、发布后打开index.html添加以下方法
其中unityInstance.SendMessage(“GetCookie”, “ReciveCookieMsg”, returnArg);
“GetCookie”:场景中"GetCookie"物体挂载的"GetCookie"脚本
“ReciveCookieMsg”:"GetCookie"脚本里的"ReciveCookieMsg"方法
<script>
function setCookie(cname, cvalue, exdays) { //exdays表示天数
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
//alert("thisPrice " + cvalue);
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var returnArg; //传出去的参数
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) {
returnArg = c.substring(name.length, c.length);
console.log("lastMassage: " + returnArg);
unityInstance.SendMessage("GetCookie", "ReciveCookieMsg", returnArg);
return; // returnArg;
}
}
return "";
}
</script>