如何让Unity打包的WebGL与Js进行通信

 使用Unity发布WebGL项目免不了要与Js进行通信,所以整理下相关知识。

一 Unity调用Js方法

1.弃用的方法
(1)在发布的WebGL项目的index.html添加Exit函数:

function Exit() { alert("UnityToWeb") }

(2)如果想在Unity中调用方法,添加代码:

Application.ExternalCall("Exit");//调用Js的Exit方法

2.新方法
(1) 新建文件夹Plugins
(2) 文件夹新建.jslib文件,这里创建__Internal.jslib文件
添加代码

mergeInto(LibraryManager.library, {

  Hello: function () {
    window.alert("Hello, world!");
	Exit();//调用Js方法
  },
});

(3)c#文件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
/// 
/// Unity调用Js
/// 
public class UnityToWeb : MonoBehaviour
{
//引入方法
    [DllImport("__Internal")]
    private static extern void Hello();

    void Start()
    {
        Hello();//调用定义方法
    }

/// 
/// Unity调用JSExit方法
/// 
public void Exit()
    {
       // Application.ExternalCall("Exit");
    }
}

(5)在发布的WebGL项目的index.html添加Exit函数:

function Exit() { alert("UnityToWeb") }

二 Js调用Unity方法

1.在场景中新建空物体,命名WebWithUnity,然后在新建脚本WebToUnity。

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

public class WebToUnity : MonoBehaviour
{
    public Text text;
    public void JsToUnity(string a)
    {
        text.text = a;
    }
}

2.这里,我们要在Js中调用JsToUnity这个函数,将项目打包后,修改index.html文件。`



  
    
    
    Unity WebGL Player | RoamWeb
    
    
    
    
    
  
  
    

你可能感兴趣的:(Unity,Web,WebGL,html5,Js)