Unity WebGL與JS腳本交互


1.Unity調用JavaScript腳本方法

官網文檔

老版本方法

之前Unity提供的Application.ExternalCall方法現在已經被設為過時棄用。(但是現在還能用,但是不知道什么時候可能就不能用了)

 

Unity發送消息給JS

 

unity想要和js交互,提供了一個函數:Application.ExternalCall();此函數僅限於web平台下。我們編輯發布的html文件,在里面加入我們的js腳本方法如下:

需要家<script></script>標簽

function GetID(id)
{
   alert("序號:"+id);    
}

 

unity里面使用

Application.ExternalCall("GetID","大概看了");

 

新版本方法

 

1.首先在Plugins文件下創建后綴為.jslib 文件,將瀏覽器腳本寫在里面

 

格式如下:

mergeInto(LibraryManager.library, 
{
 
  Hello: function ()
  {
    window.alert("Hello, world!");
  },
 
  HelloString: function (str) 
  {
    window.alert(Pointer_stringify(str));
   
  },
 
   HelloFloat: function () 
   {
       return 1;
   },
 
 });

這里可以添加若干個方法,方法之間記得用逗號隔開,否則WebGL平台打包的時候會報錯

 

2.新建C#腳本引用Js方法(unity調用JS)

格式如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using UnityEngine.UI;
public class CallJs : MonoBehaviour
{ 

    [DllImport("__Internal")]
    public  static extern void Hello();

    [DllImport("__Internal")]
    public static extern void HelloString(string str);
    [DllImport("__Internal")]
    public static extern int  HelloFloat();
  
}

 

3.最后是測試腳本

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Btn : MonoBehaviour
{
    public Button btn1;
    public Button btn2;
    public Button btn3;
    public InputField inputField;
    // Start is called before the first frame update
    void Start()
    {
        btn1.onClick.AddListener(delegate {

            Debug.Log(1);
            CallJs.Hello();
        });
        btn2.onClick.AddListener(delegate {

            Debug.Log(2);
            CallJs.HelloString("這是JS");
        });
        btn3.onClick.AddListener(delegate {

            Debug.Log(CallJs.HelloFloat());
        });
    }
   
}

 

4.打包測試即可(測試結果如下)

 

 

 

5.JS調用Unity方法

測試腳本方法如下

 

 

 

需要在打包好的html文件里面加入要調用的方法(打webgl包里有有index.html編輯此文件測試即可)

下面是測試方法 (放到<body></body>里面)

unityInstance.SendMessage("GameManager","測試JS2","這是JS啊");
里面三個參數依次是:場景中掛載腳本(CallJs)物體的名字,你寫的腳本方法,需要傳的參數
  <button id="lool">測試</button>
    <button id="lool1">測試1</button>
    <script>
      function Hello(){
   unityInstance.SetFullscreen(0);
   unityInstance.SendMessage("GameManager","測試JS1");
console.log(unityInstance);
      };
      document.getElementById("lool").onclick=Hello;
      
      document.getElementById("lool1").onclick=function(){
        // unityInstance.SetFullscreen(0);
   unityInstance.SendMessage("GameManager","測試JS2","這是JS啊");
      };
    </script>

 

測試結果

點擊測試出現

 

 

 

 

 

點擊測試1出現

 

 

 

 

 

具體擴展看項目需要自己加就行了

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM