Unity如何调用页面Js的方法
1.首先在index.html页面添加一个有返回值的方法 init()
<!DOCTYPE html>
<html lang="en-us" xmlns:th="http://www.w3.org/1999/xhtml">
<head id="head-css">
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>VrLab</title>
<link rel="stylesheet" th:href="@{/webGL/style.css}">
</head>
<body style="background: #0d1633" id="body-js">
<script th:src="@{/webGL/UnityProgress.js}"></script>
<script th:src="@{/webGL/UnityLoader.js}"></script>
<script>
/*<![CDATA[*/
var basePath = '[[${#httpServletRequest.getScheme() + "://" + #httpServletRequest.getServerName() + ":" + #httpServletRequest.getServerPort() + #httpServletRequest.getContextPath()}]]';
/*]]>*/
var gameInstance = UnityLoader.instantiate("gameContainer", basePath+"/webGL/***.json", {onProgress: UnityProgress});
function init(){
return basePath+"*******";
}
</script>
<div class="webgl-content" style="width:100%;height:100%">
<div id="gameContainer" style="width:100%;height:100%;"></div>
<!--<div class="footer">-->
<!--<div class="fullscreen" onclick="gameInstance.SetFullscreen(1)"></div>-->
<!--</div>-->
</div>
</body>
</html>
2.新建一个.jslib类型的文件。例如 __Internal.jslib 文件
该文件中添加如下内容
mergeInto(LibraryManager.library, {
Hello: function () {
var res= init();
//Get size of the string
var bufferSize = lengthBytesUTF8(res) + 1;
//Allocate memory space
var buffer = _malloc(bufferSize);
//Copy old data to the new one then return it
stringToUTF8(res, buffer, bufferSize);
return buffer;
},
});
该Hello方法是Unity中调用的方法,在此方法中调用了Index页面中的js方法init()
同时要注意,我的返回值是一个string字符串,当在Unity的 __Internal.jslib 中接受此返回值时要用_malloc分配内存空间,将旧数据复制到新数据中,然后将其返回
3.在你.cs文件中
[DllImport("__Internal")]
public static extern string Hello();
void Start()
{
string url = Hello();//调用定义方法
}
如此,霸业可成也。