转载于添加链接描述
实现方案
使用插件Embedded Browser2.1.0实现unity与网页交互
具体步骤
1.Unity中导入插件
2.新建Canvas,在Canvas下创建一GameObject,平铺在Canvas上
3.将网页映射到GameObject上
这一步需要给创建的BrowserGUI挂载插件脚本
首先是Brower脚本,此脚本是设置嵌入网页的URL以及一些幕布大小等参数,在这里说下,有两种嵌入方式
1.可以直接嵌入浏览器网页2.可以将html文件放入与Assets文件夹同级的BrowserAssets(必须一致,必须是这个文件夹,因为若放Assets下面,会自动默认为代码为UnityScript而不是JavaScript),加载嵌入,这种方式相对快一些。
再一个就是挂载GUI Brower UI脚本,这脚本是构建UI的一个作用,请求的网页会显示出来是因为这个脚本,并且会自动添加上Raw Image组件
Unity通过插件与网页的交互
1.Unity接收网页操作做出响应
C#监听代码:
js代码:
Tips:Unity接收网页推送事件RegisterFunction(“MethodName”,CallBack);
即:网页进行一系列操作,unity中监听到并响应执行事件
2.Unity做出相应操作通知网页并更新网页显示
案例:此为unity方5秒倒计时,每轮计时结束时间重置,目标数+=3;通知网页端并显示的Demo
c# 代码:
Js代码:
Tips:网页监听Unity操作:browser.CallFunction(“MethodName”,params).Down();
即:unity进行一系列操作,unity通知网页自身变化并调用网页更新函数
完整代码
场景1:网页点击按钮,Unity接收参数:
c#:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using ZenFulcrum.EmbeddedBrowser;
using UnityEngine.SceneManagement;
/// <summary>
/// Unity使用插件控制脚本
/// </summary>
public class DemoTexMgr : MonoBehaviour
{
/// <summary>
/// 插件组件
/// </summary>
Browser browser;
/// <summary>
/// 监听H5操作作出响应物体
/// </summary>
public Transform targetScle;
/// <summary>
/// 嵌入网页地址
/// </summary>
string URL = "file:///C:/Users/lenovo/Desktop/工作/自测需要/测试Js脚本/TextTool.html";
/// <summary>
/// 目标位置(显示同步到H5)
/// </summary>
private Vector3 targetPos;
public Vector3 TargetPos { get; set; }
private void Awake()
{
//获取插件Browser组件(Unity方使用插件基础一步)
browser = transform.Find("BrowserGUI").GetComponent<Browser>();
}
void Start()
{
InitData();
}
public void Update()
{
}
/// <summary>
/// 初始化函数(初始化嵌入页面)
/// </summary>
public void InitData()
{
//设置嵌入页面网址
browser.Url = URL;
//插件前往函数
browser.GoForward();
//browser.gameObject.GetComponent<RawImage>().raycastTarget = false;
//改变背景深度(透明度)
browser.gameObject.GetComponent<RawImage>().color = new Color(browser.gameObject.GetComponent<RawImage>().color.r, browser.gameObject.GetComponent<RawImage>().color.b, browser.gameObject.GetComponent<RawImage>().color.g, 20);
//插件中监听函数,监听H5操作(点击缩小按钮,Unity做出缩小响应)
browser.RegisterFunction("displayDate", (JSONNode jk) =>
{
Debug.Log("yuanjun Unity Get H5 参数" + jk[0].AsJSON + " 参数 " + jk[1].AsJSON + " " + jk[0].Value);
targetScle.transform.localScale = new Vector3(0.8f, 0.8f, 0.8f);
});
browser.RegisterFunction("GetUniMethodty", (JSONNode jk) =>
{
targetScle.transform.localScale = new Vector3(float.Parse(jk[0].AsJSON), 0.8f, 0.8f);
Debug.Log("yuanjun Unity Get H5 GetUniMethodty 参数1" + jk[0].AsJSON);
});
}
//退出按钮
public void OnClickQuitBtn()
{
Application.Quit();
}
public void ChangeBtn()
{
SceneManager.LoadScene(1);
}
}
js脚本:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>类似于Jquery的JS下拉菜单</title>
<style type="text/css">
* { margin: 0; padding: 0; font-style: normal; font-family: 宋体; }
body { text-align: center; font-size: 12px; background:url(1.jpg) center center; }
#content { margin: 0 auto; width: 600px; }
#content #nav { height: 32px; margin-top: 60px; background-color: #464749;FILTER: alpha(opacity=80); opacity: 0.8; -moz-opacity: 0.8; }
#content #nav ul { list-style: none; }
#content #nav ul li { float: left; width: 100px; line-height: 32px; position: relative; }
#nav div { width: 100px;FILTER: alpha(opacity=80); opacity: 0.8; -moz-opacity: 0.8; position:absolute; left:0px; top:32px; z-index:1; padding-bottom: 0px; float: left; height: 0; overflow: hidden; background-color: #fff;color:#000; }
#content #nav li .a { text-decoration: none; color: #FFFFFF; line-height: 32px; display: block; border-right-width: 1px; border-right-style: solid; border-right-color: #393A3C; }
#nav div a { text-decoration: none; color: #000; line-height: 26px; display: block; z-index:100; }
#nav div a:hover { background-color: #ccc; }
</style>
</head>
<body>
<div id="content">
<div id="nav">
<ul id="supnav">
<li><a href="#" class="a">物体变大</a>
<div>
<button onclick="GetUniMethodty(5)">变大</button>
</div>
</li>
<li><a href="#" class="a">物体旋转</a>
<div>
<a href="#">物体旋转</a>
</div>
</li>
<li><a href="#" class="a">物体缩小</a>
<div>
<button onclick="displayDate(1,2)">缩小</button>
</div>
</li>
<li><a href="#" class="a">导航菜单</a>
<div>
<a href="#">导航菜单</a>
</div>
</li>
<li><a href="#" class="a">导航菜单</a>
<div>
<a href="#">导航菜单</a>
</div>
</li>
<li><a href="#" class="a">导航菜单</a>
<div>
<a href="#">导航菜单</a>
</div>
</li>
</ul>
</div>
</div>
<script type="text/javascript">
var supnav = document.getElementById("supnav");
var nav = document.getElementById("nav");
var btns = document.getElementsByTagName("li");
var subnavs = nav.getElementsByTagName("div");
var paddingbottom = 20;
var defaultHeight = 0;
function drop(obj, ivalue) {
var a = obj.offsetHeight;
var speed = (ivalue - obj.offsetHeight) / 8;
a += Math.floor(speed);
obj.style.height = a + "px";
}
window.onload = function() {
for (var i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onmouseover = function() {
var osubnav = subnavs[this.index];
var sublinks = osubnav.getElementsByTagName("a");
if (osubnav.firstChild.tagName == undefined) {
var itarheight = parseInt(osubnav.childNodes[1].offsetHeight) * sublinks.length + paddingbottom;
} else {
var itarheight = parseInt(osubnav.firstChild.offsetHeight) * sublinks.length + paddingbottom;
}
clearInterval(this.itimer);
this.itimer = setInterval(function() {
drop(osubnav, itarheight);
},
30);
}
btns[i].onmouseout = function() {
var osubnav = subnavs[this.index];
clearInterval(this.itimer);
this.itimer = setInterval(function() {
drop(osubnav, defaultHeight);
},
30);
}
}
}
</script>
<script>
function displayDate(a,b){
alert("DisPlayData " +a );
return a+b;
}
</script>
<script>
function GetUniMethodty(s){
alert("Data Come " +s);
return s;
}
</script>
<script>
function myFunction(){
alert("Welcome " + "Harry Potter ");
}
</script>
</body>
</html>
场景2:Unity中Cube移动位置,网页上位置信息更新
c#:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using ZenFulcrum.EmbeddedBrowser;
using UnityEngine.SceneManagement;
public class DemoTesxMgrOne : MonoBehaviour
{
/// <summary>
/// 插件组件
/// </summary>
Browser browser;
/// <summary>
/// 监听H5操作作出响应物体
/// </summary>
public Transform targetScle;
/// <summary>
/// 嵌入网页地址
/// </summary>
string URL = "file:///C:/Users/lenovo/Desktop/工作/自测需要/测试Js脚本/demo.html";
/// <summary>
/// 目标位置(显示同步到H5)
/// </summary>
public delegate void del(Vector3 v);
public del _del;
public Vector3 oldv;
private Vector3 targetPos;
public Vector3 TargetPos {
get {
return targetPos;
}
set
{
targetPos = value;
if (oldv!=targetPos)
{
_del(targetPos);
oldv=targetPos;
}
} }
public int TextValue = 0;
public float timer = 5;
private void Awake()
{
//获取插件Browser组件(Unity方使用插件基础一步)
browser = transform.Find("BrowserGUI").GetComponent<Browser>();
_del += calH5;
// oldv = targetScle.transform.localPosition;
}
void Start()
{
InitData();
}
public void Update()
{
TargetPos = targetScle.transform.localPosition;
//if (timer > 0)
//{
// timer -= Time.deltaTime;
//}
//else
//{
// TextValue += 3;
// timer = 5;
// browser.CallFunction("selall", TextValue).Done();
//}
}
public void calH5(Vector3 v)
{
browser.CallFunction("selall", v.ToString()).Done();
}
/// <summary>
/// 初始化函数(初始化嵌入页面)
/// </summary>
public void InitData()
{
//设置嵌入页面网址
browser.Url = URL;
//插件前往函数
browser.GoForward();
//browser.gameObject.GetComponent<RawImage>().raycastTarget = false;
//改变背景深度(透明度)
browser.gameObject.GetComponent<RawImage>().color = new Color(browser.gameObject.GetComponent<RawImage>().color.r, browser.gameObject.GetComponent<RawImage>().color.b, browser.gameObject.GetComponent<RawImage>().color.g, 20);
//插件中监听函数,监听H5操作(点击缩小按钮,Unity做出缩小响应)
//browser.RegisterFunction("displayDate", (JSONNode jk) =>
//{
// Debug.Log("yuanjun Unity Get H5 参数" + jk[0].AsJSON + " 参数 " + jk[1].AsJSON + " " + jk[0].Value);
// targetScle.transform.localScale = new Vector3(0.8f, 0.8f, 0.8f);
//});
//browser.RegisterFunction("GetUniMethodty", (JSONNode jk) =>
//{
// targetScle.transform.localScale = new Vector3(float.Parse(jk[0].AsJSON), 0.8f, 0.8f);
// Debug.Log("yuanjun Unity Get H5 GetUniMethodty 参数1" + jk[0].AsJSON);
//});
}
//unity调试
public void OnClickJsData()
{//调用页面中任何可用的js(自上而下)
// browser.EvalJS("displayDate(7,5)").Then(Result =>
// { Debug.Log(Result.Value); }
//).Done();
// //查询页面中的数据,可以查看返回值(测试多返回值时好像只返回最后一个值)
//browser.CallFunction("displayDate", 1, 2).Then(Result =>
//{
// Debug.Log(" displayDate " + Result.Value);
//});
// browser.CallFunction("selall", 100).Done();
}
//退出按钮
public void OnClickQuitBtn()
{
Application.Quit();
}
public void ChangeBtn()
{
SceneManager.LoadScene(0);
}
}
Tips:注意以上有不少冗余代码,为什么用两个场景两个网页测试,归根结底是因为我不懂Js,我想要的事件一个无法满足还不会扩展,所以,重点看方法不看代码。
我也只是跑通了,里面还有很多方法函数,我这里只是先实现了互通,理解可能不准确或者不对,热烈欢迎指出并交流。
最近:最近在做demo时,具体遇到了这么几点:
1.上面在嵌入网页时需要挂在GUI Brower UI脚本,但是在我做demo时发现,这个脚本在这个版本还可以用,但是已被编辑为过时[Obsolete(“Use PointerUIGUI and CursorRendererOS instead.”)],应用PointerUIGUI脚本替代。
js代码:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Ventilation UI</title>
<style>
html {
height: 100%;
}
body
{
font-family: Monospace;
font-weight: bold;
background-color: #ccccff00;
margin: 0px;
height: 100%;
overflow: hidden;
}
</style>
</head>
<body>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<div class="container">
<div class="btn-toolbar " role="toolbar" aria-label="Toolbar">
<div class="btn-group mr-2" role="group" aria-label="First Group">
<button id="createLaneway" type="button" class="btn btn-success">新建</button>
<button id="editLaneway" type="button" class="btn btn-success">编辑</button>
<button id="drawAirDuct" type="button" class="btn btn-success">绘制</button>
<button id="drawAirDoor" type="button" class="btn btn-success">绘制</button>
<button id="drawLine" type="button" class="btn btn-success">画线</button>
<button id="drawFace" type="button" class="btn btn-success">画面</button>
</div>
<div class="btn-group mr-2" role="group" aria-label="Second Group">
<button type="button" class="btn btn-success">平移</button>
<button type="button" class="btn btn-success">旋转</button>
<button type="button" class="btn btn-success">缩放</button>
</div>
<div class="btn-group" role="group" aria-label="Fourth group">
<button id="undo" type="button" class="btn btn-success">撤销</button>
<button id="redo" type="button" class="btn btn-success">重做</button>
<button id="none" type="button" class="btn btn-success">退出编辑</button>
<button id="exit" type="button" class="btn btn-success">退出程序</button>
</div>
</div>
</div>
<script>
$('#createLaneway').on('click', function () { onCreateLane(); });
$('#editLaneway').on('click', function () { onEditLane(); });
$('#drawAirDuct').on('click', function () { onDrawDuct(); });
$('#drawAirDoor').on('click', function () { onDrawDoor(); });
$('#drawLine').on('click', function () { onDrawLine(); });
$('#drawFace').on('click', function () { onDrawFace(); });
$('#undo').on('click', function () { onUndo(); });
$('#redo').on('click', function () { onRedo(); });
$('#none').on('click', function () { onExitEdit(); });
$('#exit').on('click', function () { onExit(); });
function onCreateLane(e) {
console.log('新建');
}
function onEditLane(e) {
console.log('编辑');
}
function onDrawDuct(e) {
console.log('绘制');
}
function onDrawDoor(e) {
console.log('绘制');
}
// 画线事件响应
function onDrawLine(e) {
console.log('画线');
}
// 画面事件响应
function onDrawFace(e) {
console.log('画面');
}
// 撤销事件响应
function onUndo(e) {
console.log('撤销');
}
// 重做事件响应
function onRedo(e) {
console.log('重做');
}
function onExitEdit() {
console.log('退出编辑');
}
function onExit() {
console.log('退出');
}
//加载结束
function loadEnd() {
console.log("Load end");
}
window.onload = function () { loadEnd(); }
</script>
</body>
</html>
这种注册按钮的方式,按着我之前说的那中监听方式会监听不到,
如: (’#createLaneway’).on(‘click’, function () { onCreateLaneway(); });这句注册按钮代码,如果写成(’#createLaneway’).on(‘click’, onCreateLaneway() );就会监听不到,所以外面套了个function () { },就可以了。
3.比如你要加载完H5页面再执行逻辑,browser.WhenLoaded(StartApp());使用browser.WhenLoaded()函数,里面传Action参数,在里面可以处理写加载完页面后你想处理的事件。
4.请求地址可以在最后面写:browser.WhenReady(SetRequestURL());使用browser.WhenReady()这个函数,里面传Action参数,在里面写请求地址。如:
private Action SetRequestURL()
{
return delegate ()
{
// 设置Url地址
browser.Url = "localGame://index.html";
};
}