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出现

 

 

 

 

 

具体扩展看项目需要自己加就行了

 

 

 

 

 

posted @   剑起苍穹  阅读(2382)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
/*鼠标点击特效*/
点击右上角即可分享
微信分享提示