1. Unity pass value to js
in unity:
void Awake()
{
Application.ExternalCall("GetCookie");//GetCookie参数是js方法名字
}
js:
function GetCookie() {
//var result = document.URL;//获取地址
var result = document.location.href;//获取地址
if (result != "") {
var result = decodeURIComponent(result);
}
console.log("发送消息:Cookie,OnCookie_Callback");
unityInstance.SendMessage("Cookie", "OnCookie_Callback", result);
}
2. js pass value to unity
Parameter 1 Cookie: the name of the object in the scene (the name of the uppermost parent object, otherwise the value cannot be passed successfully)
Parameter 2 OnCookie_Callback: method name
Parameter 3 result: value
unityInstance.SendMessage("Cookie","OnCookie_Callback",result);
in unity:
public void OnCookie_Callback(string cookie)
{
Debug.Log("收到cookie=" + cookie);
}
whole:
The name of the object in the unity scene
Untiy code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
private string NextSceneName;
void Awake()
{
Application.ExternalCall("GetCookie");//GetCookie参数是js方法名字
}
public void OnCookie_Callback(string cookie)
{
Debug.Log("收到cookie=" + cookie);
}
}
js code:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unity WebGL Player | Test999</title>
<link rel="shortcut icon" href="TemplateData/favicon.ico">
<link rel="stylesheet" href="TemplateData/style.css">
<script src="TemplateData/UnityProgress.js"></script>
<script src="Build/UnityLoader.js"></script>
<script>
var unityInstance = UnityLoader.instantiate("unityContainer", "Build/Test99.json", {onProgress: UnityProgress});
function GetCookie() {
var result = document.URL;//获取地址
// var result = document.location.href;//获取地址
console.log("发送消息:Cookie,OnCookie_Callback");
gameInstance.SendMessage("Cookie", "OnCookie_Callback", result);
}
</script>
</head>
<body>
<div class="webgl-content">
<div id="unityContainer" style="width: 960px; height: 600px"></div>
<div class="footer">
<div class="webgl-logo"></div>
<div class="fullscreen" onclick="unityInstance.SetFullscreen(1)"></div>
<div class="title">Test999</div>
</div>
</div>
</body>
</html>