效果
游戏对象绑定脚本
游戏脚本源码
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;publicclassTent:MonoBehaviour{publicCamera camera;// Start is called before the first frame updatevoidStart(){}// Update is called once per frame[System.Obsolete]voidUpdate(){SendUnityMessage();}/// <summary>/// 发送数据到Web端/// </summary>[System.Obsolete]publicvoidSendUnityMessage(){// 当前游戏对象的位置Vector3 worldPoint = transform.position;// 转换为屏幕位置Vector3 screenPoint = camera.WorldToScreenPoint(worldPoint);// w屏宽, h屏高, x位置, y位置Vector4 position =newVector4(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>publicvoidReceiveWebMessage(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%;}
<!DOCTYPEhtml><htmllang="en-us"><head><metacharset="utf-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Unity WebGL Player</title><linkrel="shortcut icon"href="TemplateData/favicon.ico"><linkrel="stylesheet"href="TemplateData/style.css"><linkrel="manifest"href="manifest.webmanifest"></head><body><canvasid="unity-canvas"width=900height=600tabindex="-1"></canvas><svgid="unity-svg"><textid="svg-text"></text></svg></div><scriptsrc="./js/[email protected]"></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 位置信息
*/functionupdatePosition2Web(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>
本文转载自: https://blog.csdn.net/weixin_43526371/article/details/143260755
版权归原作者 Prosper Lee 所有, 如有侵权,请联系我们删除。
版权归原作者 Prosper Lee 所有, 如有侵权,请联系我们删除。