- unity 調用瀏覽器 js
直接看 官方文檔 調用沒什么問題,傳值都可以
- js 調用 unity 方法
首先在 webgl 打包好的 index.html中寫一個按鈕,用來觸發我們的js
Script部分寫在打包生成的js段落中就可以了
1 var script = document.createElement("script"); 2 var gameInstance = null; 3 script.src = loaderUrl; 4 script.onload = () => { 5 createUnityInstance(canvas, config, (progress) => { 6 progressBarFull.style.width = 100 * progress + "%"; 7 }).then((unityInstance) => { 8 gameInstance = unityInstance; 9 loadingBar.style.display = "none"; 10 fullscreenButton.onclick = () => { 11 unityInstance.SetFullscreen(1); 12 }; 13 }).catch((message) => { 14 alert(message); 15 }); 16 }; 17 document.body.appendChild(script);
18 var button = document.querySelector("#on-number"); 19 button.onclick = function() { 20 //調用函數 SendMessage 21 gameInstance.SendMessage('Player', 'OnNumber', parseInt(Math.random()*(99)+1,10)); 22 }
button.onclick 用來觸發 SendMessage 方法,調用 Unity 中公開暴露的方法 OnNumber
注意點:需要 定義一個 gameInstance 並且暴露出來,在 createUnityInstance 后接收到 unityInstance 並儲存,代碼第2、第8行。
很多教程/博客並不會說明白這一點,而直接上示例unityInstance.SendMessage發送消息。
unityInstance 並不是可以直接調用的,需要我們獲取。
否則就會出現報錯 unityInstance/gameInstance is undefined