Unity如何调用页面Js的方法

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();//调用定义方法
        }

如此,霸业可成也。

参考:https://www.it1352.com/1873938.html

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值