WEBGL与网页相互通讯
1.webgl调用web页面的js方法:
usingSystem.Collections;
usingSystem.Collections.Generic;
usingUnityEngine;
usingUnityEngine.UI;
publicclassWEGLTest:MonoBehaviour{
Buttonbtn;
Imageimg;
voidAwake(){
btn=GetComponent<Button>();
img=btn.GetComponent<Image>();
btn.onClick.AddListener(()=>{
CallWebFunc();
} );
}
///从WEBGL调用js方法(WEBGL_TEST)并传参obj(www.baidu.com)
publicvoidCallWebFunc()
{
object[] obj = new object[]{"www.baidu.com";} ;
Application.ExternalCall("WEBGL_TEST",obj);
}
///从页面来调用WEGBL的以下方法。在WEBGL的index页面中使用来调用:setTimeout(function () { gameInstance.SendMessage("Button", "JStoWEBGL"); }, 3000);
publicvoidJStoWEBGL()
{
img.color=Color.red;
}
}
2.web页面调用unity方法:修改webgl页面的index:
<!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 | UGUI</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 gameInstance = UnityLoader.instantiate("gameContainer", "Build/WEBGL_TEST.json", {onProgress: UnityProgress});
setTimeout(function () { gameInstance.SendMessage("Button", "JStoWEBGL"); }, 3000);
function WEBGL_TEST(value)
{
window.location.href=value;
}
</script>
</head>
<body>
<div class="webgl-content">
<div id="gameContainer" style="width: 960px; height: 600px"></div>
<div class="footer">
<div class="webgl-logo"></div>
<div class="fullscreen" onclick="gameInstance.SetFullscreen(1)"></div>
<div class="title">UGUI</div>
</div>
</div>
</body>
</html>