csharp
复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tent : MonoBehaviour
{
public Camera camera;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
[System.Obsolete]
void Update()
{
SendUnityMessage();
}
/// <summary>
/// 发送数据到Web端
/// </summary>
[System.Obsolete]
public void SendUnityMessage() {
// 当前游戏对象的位置
Vector3 worldPoint = transform.position;
// 转换为屏幕位置
Vector3 screenPoint = camera.WorldToScreenPoint(worldPoint);
// w屏宽, h屏高, x位置, y位置
Vector4 position = new Vector4(Screen.width, Screen.height, screenPoint.x, Screen.height - screenPoint.y);
// 发送到Web端
Application.ExternalCall("updatePosition2Web", transform.gameObject.name, position);
}
/// <summary>
/// 接收来自Web的传参
/// </summary>
/// <param name="message">传参信息</param>
public void ReceiveWebMessage(string message) {
transform.position = Vector3.zero;
Debug.Log(message);
}
}
html
复制代码
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Unity WebGL Player</title>
<link rel="shortcut icon" href="TemplateData/favicon.ico">
<link rel="stylesheet" href="TemplateData/style.css">
<link rel="manifest" href="manifest.webmanifest">
</head>
<body>
<canvas id="unity-canvas" width=900 height=600 tabindex="-1"></canvas>
<svg id="unity-svg">
<text id="svg-text"></text>
</svg>
</div>
<script src="./js/d3@7.js"></script>
<script>
var canvas = document.querySelector("#unity-canvas");
let unity = null;
var buildUrl = "Build";
var loaderUrl = buildUrl + "/XXXXXX.loader.js";
var config = {
dataUrl: buildUrl + "/XXXXXX.data.unityweb",
frameworkUrl: buildUrl + "/XXXXXX.framework.js.unityweb",
codeUrl: buildUrl + "/XXXXXX.wasm.unityweb",
streamingAssetsUrl: "StreamingAssets",
companyName: "DefaultCompany",
productName: "XXXXXX",
productVersion: "0.1",
};
var script = document.createElement("script");
script.src = loaderUrl;
script.onload = () => {
createUnityInstance(canvas, config, (progress) => {
console.log('progress', progress);
}).then((unityInstance) => {
unity = unityInstance;
}).catch((message) => {
alert(message);
});
};
document.body.appendChild(script);
/**
* 获取游戏对象相对于屏幕的位置
* @param name 游戏对象名称
* @param position 位置信息
*/
function updatePosition2Web(name, position) {
const [w, h, x, y] = position.replace(/[()\s]/g, '').split(',');
const svg = d3.select('#unity-svg').attr('viewBox', [0, 0, w, h]);
d3.select('#svg-text')
.text(position)
.attr('x', x)
.attr('y', y)
.attr('fill', 'red')
.attr('font-size', 30)
.on('click', e => {
console.log(name, unity);
unity.SendMessage(name, "ReceiveWebMessage", "发送消息到unity!!!")
});
}
</script>
</body>
</html>