Unity2020.3 Webgl 与 Js交互

本文介绍了一种针对Unity 2020版本的特殊打包方法,通过创建特定的JSLib文件和脚本来实现在WebGL中调用原生浏览器功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考很多网上的方法,我发现2020版本和2020之前版本打包后的index.html文件简直天差地别,大多数按照网上的方法在2020版本上是无法实现的,所以我结合了网上的方法进行了改进:

  1. 新建一个txt文本,改名为__Internal更改文件格式为jslib,此文件必须放在Plugins文件夹下(没有此文件夹自己创建一个即可)。内容如下:
mergeInto(LibraryManager.library, {
  SayHello:function(){
  window.alert("Hello World!");
  },
  ReportReady:function(){
  window.ReportReady();
  }
});
  1. 创建一个脚本,脚本名称随意(我这里暂定为Script);创建一个脚本,名称随意,将创建好的脚本挂载在Scripts节点上,脚本内容如下:
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;

public class WebglOpenUrlTest : MonoBehaviour
{
    public Text _Text;
    
    [DllImport("__Internal")]
    private static extern void SayHello();

    [DllImport("__Internal")]
    private static extern void ReportReady();

    private void Start()
    {
        ReportReady();
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            SayHello();
        }
    }

    public void GetInfo(string s)
    {
        _Text.text = s;
    }
}

3.打Webgl包,打包完成后找到index.html文件,修改html文件,这里是我的html文件:

<!DOCTYPE html>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>Webgl</title>
    <link rel="shortcut icon" href="TemplateData/favicon.ico">
    <link rel="stylesheet" href="TemplateData/style.css">
  </head>
  <body class="dark">
    <div id="unity-container" class="unity-desktop">
      <canvas id="unity-canvas"></canvas>
    </div>
    <div id="loading-cover" style="display:none;">
      <div id="unity-loading-bar">
        <div id="unity-logo"><img src="logo.png"></div>
        <div id="unity-progress-bar-empty" style="display: none;">
          <div id="unity-progress-bar-full"></div>
        </div>
        <div class="spinner"></div>
      </div>
    </div>
    <div id="unity-fullscreen-button" style="display: none;"></div>
    <script>
      const hideFullScreenButton = "";
      const buildUrl = "Build";
      const loaderUrl = buildUrl + "/TTT.loader.js";
      const config = {
        dataUrl: buildUrl + "/TTT.data",
        frameworkUrl: buildUrl + "/TTT.framework.js",
        codeUrl: buildUrl + "/TTT.wasm",
        streamingAssetsUrl: "StreamingAssets",
        companyName: "DefaultCompany",
        productName: "Webgl",
        productVersion: "0.1",
      };

      const container = document.querySelector("#unity-container");
      const canvas = document.querySelector("#unity-canvas");
      const loadingCover = document.querySelector("#loading-cover");
      const progressBarEmpty = document.querySelector("#unity-progress-bar-empty");
      const progressBarFull = document.querySelector("#unity-progress-bar-full");
      const fullscreenButton = document.querySelector("#unity-fullscreen-button");
      const spinner = document.querySelector('.spinner');

      const canFullscreen = (function() {
        for (const key of [
            'exitFullscreen',
            'webkitExitFullscreen',
            'webkitCancelFullScreen',
            'mozCancelFullScreen',
            'msExitFullscreen',
          ]) {
          if (key in document) {
            return true;
          }
        }
        return false;
      }());

      if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
        container.className = "unity-mobile";
        config.devicePixelRatio = 1;
      }
      loadingCover.style.display = "";

      const script = document.createElement("script");
      script.src = loaderUrl;
     //全局
     const gameInstance=null ;

      script.onload = () => {
        createUnityInstance(canvas, config, (progress) => {
          spinner.style.display = "none";
          progressBarEmpty.style.display = "";
          progressBarFull.style.width = `${100 * progress}%`;
        }).then((unityInstance) => {
          
          loadingCover.style.display = "none";
          if (canFullscreen) {
            if (!hideFullScreenButton) {
              fullscreenButton.style.display = "";
            }
            fullscreenButton.onclick = () => {
              unityInstance.SetFullscreen(1);
            };
          }
            this.gameInstance=unityInstance;

        }).catch((message) => {
          alert(message);
        });
      };

      window.ReportReady=function(x,y){
        window.top.dispatchEvent(new CustomEvent(x,{detail:y}))
        send({id:1,value:2})
      }
      function send(obj){
         this.gameInstance.SendMessage('Scripts','GetInfo',JSON.stringify(obj))
      }

      document.body.appendChild(script);
    </script>
  </body>
</html>

修改添加内容如下:
在这里插入图片描述
在浏览器上运行:
在这里插入图片描述

在这里插入图片描述
参考:https://blog.youkuaiyun.com/weixin_44957482/article/details/114658245)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值