Unity Webgl内嵌网页页面

Unity Webgl端有时候会有这样一个需求,在Unity界面上内嵌一个网页,并且可以在界面上把这个网页关掉(不是重新打开新的标签页)

效果如下:
在这里插入图片描述
现在来实现这个功能:
1.在Assets文件夹下新建一个Plugins目录:
在这里插入图片描述
在Plugins文件夹中创建一个文件 __Internal.jslib (必须是jslib格式,并且必须在Plugins文件夹下)
__Internal.jslib内容如下:

mergeInto(LibraryManager.library, {
  //开启新窗口
  OpenUrlWindow:function(str) 
  {
      OpenUrl_Window(Pointer_stringify(str)); //调用js方法
  },
  //关闭新窗口
  CloseUrlWindow:function()
  {
      CloseUrl_Window();//调用js方法
  },
});

2.新建一个脚本 脚本内容如下:


using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;

public class WebglOpenUrlTest : MonoBehaviour
{
    /// <summary>
    /// 需要打开的链接
    /// </summary>
    public string url;

    public Button Btn_NewWin;
    public Button Btn_CloseWin;

    [DllImport("__Internal")]
    private static extern void OpenUrlWindow(string str);

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


    void Start()
    {
        Btn_NewWin.onClick.AddListener(delegate
        {
            OpenUrlWindow(url);
        });
        Btn_CloseWin.onClick.AddListener(delegate
        {
            CloseUrlWindow();
        });
    }
}

将该脚本挂载在物体对象上
在这里插入图片描述
打Webgl包,打包完成后,打包文件夹中会有一个index.html文件
在这里插入图片描述
打开文件添加以下内容:
在这里插入图片描述
在这里插入图片描述
我的index.html如下:

<!DOCTYPE html>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Unity WebGL Player | 水库3D模型</title>
    <link rel="shortcut icon" href="TemplateData/favicon.ico">
    <link rel="stylesheet" href="TemplateData/style.css">
  </head>
  <body>
    <div id="unity-container" class="unity-desktop">
      <canvas id="unity-canvas" width=1920 height=1080></canvas>
      <div id="unity-loading-bar">
        <div id="unity-logo"></div>
        <div id="unity-progress-bar-empty">
          <div id="unity-progress-bar-full"></div>
        </div>
      </div>
      <div id="unity-warning"> </div>
      <div id="unity-footer">
        <div id="unity-webgl-logo"></div>
        <div id="unity-fullscreen-button"></div>
        <div id="unity-build-title">水库3D模型</div>
      </div>
    </div>
        <div id="urlWindow" style="display:none;width:1000px;height:600px;top: 50%;left:50%;transform: translate(-50%,-50%);position:absolute;border: 0; margin: 0; padding: 0">  
    <iframe id="iframe" src="" style="width: 100%;height: 100%;"></iframe>   
    </div>
    <script>
      var container = document.querySelector("#unity-container");
      var canvas = document.querySelector("#unity-canvas");
      var loadingBar = document.querySelector("#unity-loading-bar");
      var progressBarFull = document.querySelector("#unity-progress-bar-full");
      var fullscreenButton = document.querySelector("#unity-fullscreen-button");
      var warningBanner = document.querySelector("#unity-warning");

      // Shows a temporary message banner/ribbon for a few seconds, or
      // a permanent error message on top of the canvas if type=='error'.
      // If type=='warning', a yellow highlight color is used.
      // Modify or remove this function to customize the visually presented
      // way that non-critical warnings and error messages are presented to the
      // user.
      function unityShowBanner(msg, type) {
        function updateBannerVisibility() {
          warningBanner.style.display = warningBanner.children.length ? 'block' : 'none';
        }
        var div = document.createElement('div');
        div.innerHTML = msg;
        warningBanner.appendChild(div);
        if (type == 'error') div.style = 'background: red; padding: 10px;';
        else {
          if (type == 'warning') div.style = 'background: yellow; padding: 10px;';
          setTimeout(function() {
            warningBanner.removeChild(div);
            updateBannerVisibility();
          }, 5000);
        }
        updateBannerVisibility();
      }

      var buildUrl = "Build";
      var loaderUrl = buildUrl + "/OpenUrlWebgl.loader.js";
      var config = {
        dataUrl: buildUrl + "/OpenUrlWebgl.data",
        frameworkUrl: buildUrl + "/OpenUrlWebgl.framework.js",
        codeUrl: buildUrl + "/OpenUrlWebgl.wasm",
        streamingAssetsUrl: "StreamingAssets",
        companyName: "DefaultCompany",
        productName: "水库3D模型",
        productVersion: "0.1",
        showBanner: unityShowBanner,
      };

      // By default Unity keeps WebGL canvas render target size matched with
      // the DOM size of the canvas element (scaled by window.devicePixelRatio)
      // Set this to false if you want to decouple this synchronization from
      // happening inside the engine, and you would instead like to size up
      // the canvas DOM size and WebGL render target sizes yourself.
      // config.matchWebGLToCanvasSize = false;

      if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
        container.className = "unity-mobile";
        // Avoid draining fillrate performance on mobile devices,
        // and default/override low DPI mode on mobile browsers.
        config.devicePixelRatio = 1;
        unityShowBanner('WebGL builds are not supported on mobile devices.');
      } else {
        canvas.style.width = "1920px";
        canvas.style.height = "1080px";
      }
      loadingBar.style.display = "block";

      var script = document.createElement("script");
      script.src = loaderUrl;
      script.onload = () => {
        createUnityInstance(canvas, config, (progress) => {
          progressBarFull.style.width = 100 * progress + "%";
        }).then((unityInstance) => {
          loadingBar.style.display = "none";
          fullscreenButton.onclick = () => {
            unityInstance.SetFullscreen(1);
          };
        }).catch((message) => {
          alert(message);
        });
      };
      document.body.appendChild(script);
             //打开新窗口
      function OpenUrl_Window(str) {
  var otherDiv = document.getElementById('urlWindow');
  otherDiv.style.display = "block";
  document.getElementById("iframe").src =str;
      }    
      //关闭新窗口
      function CloseUrl_Window() {
  var otherDiv = document.getElementById('urlWindow');
  otherDiv.style.display = "none";
  document.getElementById("iframe").src =
  ""
      };
    </script>
  </body>
</html>

将项目用本地服务打开即可

  • 5
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
### 回答1: Unity3D是一款强大的跨平台游戏引擎,可以用于开发2D和3D游戏。Unity3D也支持将游戏嵌入到Web网页中,以供用户通过浏览器进行访问和游玩。 首先,将Unity3D游戏嵌入到Web网页中需要使用Unity Web Player插件。Unity Web Player是一款浏览器插件,只需用户安装后,就可以在支持Unity3D的网页上运行Unity3D游戏。用户通过浏览器访问Web网页时,就可以实时加载Unity3D游戏,无需下载游戏到本地进行安装。 其次,嵌入Unity3D游戏到Web网页的过程相对简单。开发者需要首先将游戏项目导出为WebGL格式,这样网页上的引用链接将指向基于JavaScript的Unity WebGL构建。通过Unity的构建设置,可以调整游戏的分辨率、加载速度和其他配置,以适应不同的网页环境。然后,将导出的游戏文件(包含HTML,JavaScript和二进制文件)放入Web服务器中的相应文件夹中。最后,将嵌入Unity3D游戏的代码插入到Web网页的HTML文件中,以启动并显示游戏界面。 值得注意的是,随着Web技术的发展,Unity3D宣布将停止支持Unity Web Player插件,并更加推荐使用WebGL来嵌入Unity3D游戏到Web网页中。WebGL是一种基于Web标准的3D图形API,可以在不依赖插件的情况下在现代浏览器中运行。通过使用UnityWebGL构建目标,开发者可以将游戏直接导出为支持WebGL的文件,然后将这些文件部署到Web服务器中,并通过HTML的canvas标签来嵌入到Web网页中,实现无需插件的网页游戏体验。 综上所述,Unity3D支持嵌入到Web网页中,用户只需安装Unity Web Player插件或使用现代浏览器支持的WebGL技术,就可以通过浏览器访问并玩游戏。但需要注意,由于技术的发展,建议开发者使用WebGL来嵌入Unity3D游戏到Web网页中,以保持与未来发展的兼容性。 ### 回答2: Unity3D是一款强大的跨平台游戏开发引擎,可以用于创建各种类型的游戏和交互应用程序。在Unity3D中,我们可以将开发的游戏或应用程序嵌入到网页中,为用户提供在线体验的机会。 嵌入Unity3D游戏或应用程序到网页中的过程相对简单。首先,我们需要将Unity3D项目导出为网页可用的格式,例如WebGL。然后,我们可以使用HTML和JavaScript等网页技术,将导出的游戏或应用程序嵌入到网页中的特定位置。 在嵌入过程中,我们可以通过调整参数来自定义游戏或应用程序在网页中的表现形式。例如,我们可以设置窗口的大小、背景和边框的样式等。还可以通过调整Unity3D的摄像机设置,来改变游戏或应用程序在网页中的视觉效果。 嵌入Unity3D游戏或应用程序到网页中,可以为用户提供在线直接玩的体验。无需下载和安装游戏或应用程序,只需打开网页,即可开始游戏或使用应用程序。这对于开发者来说,可以减少用户的操作步骤,提高用户的参与度和体验感。同时,用户也可以在不同平台和设备上使用游戏或应用程序,无需担心兼容性问题。 总之,Unity3D的嵌入Web网页功能为开发者提供了一种方便的方式,将游戏或应用程序直接嵌入到网页中,为用户提供在线体验的机会。这样的开发方式可以节省用户的时间和精力,提高用户的满意度和参与度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值