效果
游戏对象绑定脚本
游戏脚本源码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tent : MonoBehaviour
{
public Camera camera;
void Start()
{
}
[System.Obsolete]
void Update()
{
SendUnityMessage();
}
[System.Obsolete]
public void SendUnityMessage() {
Vector3 worldPoint = transform.position;
Vector3 screenPoint = camera.WorldToScreenPoint(worldPoint);
Vector4 position = new Vector4(Screen.width, Screen.height, screenPoint.x, Screen.height - screenPoint.y);
Application.ExternalCall("updatePosition2Web", transform.gameObject.name, position);
}
public void ReceiveWebMessage(string message) {
transform.position = Vector3.zero;
Debug.Log(message);
}
}
打包为Web应用
修改打包后的HTML源码
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
#unity-canvas,
#unity-svg {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
height: 100%;
}
<!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);
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>