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