Unity打包WebGL: 导入Vue

这篇具有很好参考价值的文章主要介绍了Unity打包WebGL: 导入Vue。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Unity打包WebGL: 导入Vue

1. 介绍

1.1 任务

记录将Unity项目打包成WebGL,并集成到Vue项目中的过程。

1.2 环境

  • Unity:2021.3
  • Vue: 2

2. Unity项目

2.1 UI界面

Unity打包WebGL: 导入Vue,unity,webgl,vue.js

2.2 添加插件

构建WebGL项目需要添加一个.jslib文件,用于Unity脚本函数与JavaScript函数交互
详细内容参考:Unity(WebGL)与JS通讯2022最新姿势
Unity打包WebGL: 导入Vue,unity,webgl,vue.js

Unity打包WebGL: 导入Vue,unity,webgl,vue.js

Unity打包WebGL: 导入Vue,unity,webgl,vue.js
web.jslib文件内容

mergeInto(LibraryManager.library, {

    SayHello: function () {
        window.alert("hello vue");
    },

    ReportReady: function() {
        window.ReportReady();
    }
})

2.3 添加脚本CBtn.cs

为按钮添加脚本

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

public class CBtn : MonoBehaviour
{
    [DllImport("__Internal")]
    private static extern void SayHello();
    [DllImport("__Internal")]
    private static extern string ReportReady();

    public Text text;

    // Start is called before the first frame update
    void Start()
    {
        ReportReady();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyUp(KeyCode.H)) {
            SayHello();
        }
    }

    public void SetToken(string token) {
        this.text.text = token;
    }
}

绑定脚本

Unity打包WebGL: 导入Vue,unity,webgl,vue.js

2.4 打包WebGL

Unity打包WebGL: 导入Vue,unity,webgl,vue.js
Unity打包WebGL: 导入Vue,unity,webgl,vue.js
一些设置参考:
Unity打包WebGL: 导入Vue,unity,webgl,vue.js
Unity打包WebGL: 导入Vue,unity,webgl,vue.js
Unity打包WebGL: 导入Vue,unity,webgl,vue.js
Unity打包WebGL: 导入Vue,unity,webgl,vue.js
Unity打包WebGL: 导入Vue,unity,webgl,vue.js
构建:
Unity打包WebGL: 导入Vue,unity,webgl,vue.js
Unity打包WebGL: 导入Vue,unity,webgl,vue.js
Unity打包WebGL: 导入Vue,unity,webgl,vue.js

2.5 修改index.html

html文件引入其他js文件的格式,
具体参考: webGl使用jsLib与Js交互
Unity打包WebGL: 导入Vue,unity,webgl,vue.js

<!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 | Web with Vue</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=960 height=600></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">Web with Vue</div>
      </div>
    </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 + "/Web.loader.js";
      var config = {
        dataUrl: buildUrl + "/Web.data",
        frameworkUrl: buildUrl + "/Web.framework.js",
        codeUrl: buildUrl + "/Web.wasm",
        streamingAssetsUrl: "StreamingAssets",
        companyName: "DefaultCompany",
        productName: "Web with Vue",
        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)) {
        // Mobile device style: fill the whole browser client area with the game canvas:

        var meta = document.createElement('meta');
        meta.name = 'viewport';
        meta.content = 'width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes';
        document.getElementsByTagName('head')[0].appendChild(meta);
        container.className = "unity-mobile";
        canvas.className = "unity-mobile";

        // To lower canvas resolution on mobile devices to gain some
        // performance, uncomment the following line:
        // config.devicePixelRatio = 1;

        unityShowBanner('WebGL builds are not supported on mobile devices.');
      } else {
        // Desktop style: Render the game canvas in a window that can be maximized to fullscreen:

        canvas.style.width = "960px";
        canvas.style.height = "600px";
      }

      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";

          // 绑定unityInstance
          window.unityInstance = unityInstance

          fullscreenButton.onclick = () => {
            unityInstance.SetFullscreen(1);
          };
        }).catch((message) => {
          alert(message);
        });
      };
      document.body.appendChild(script);

      // unity调用函数
      window.ReportReady = () => {
        // window.top.dispatchEvent(new CustomEvent())
        send({
          id: 1,
          value: 2
        })
      }

      function send(obj) {
        unityInstance.SendMessage('button', 'SetToken', JSON.stringify(obj))
      }
    </script>
  </body>
</html>

3. Vue项目

3.1 项目初始化

Unity打包WebGL: 导入Vue,unity,webgl,vue.js

3.2 引入WebGL项目

Unity打包WebGL: 导入Vue,unity,webgl,vue.js

3.3 监听WebGL事件

  1. 修改App.vue
<template>
  <div id="app">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

  1. 修改HelloWorld.vue
<template>
  <div>
    <div @click="send">尝试发送数据</div>
    <iframe
      ref="iframe"
      width="1200"
      height="800"
      scrolling="no"
      src="/Unity/index.html"
      frameborder="0"></iframe>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data () {
    return {}
  },
  mounted () {
    window.addEventListener('fn', this.unityWatch)
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener('fn', this.unityWatch)
    })
  },
  methods: {
    send () {
      // 发送数据
      this.$refs.iframe.contentWindow.send({
        id: 12,
        value: 34
      })
    },
    unityWatch (e) {
      alert(e.detail)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

4. 测试

Unity打包WebGL: 导入Vue,unity,webgl,vue.js
Unity打包WebGL: 导入Vue,unity,webgl,vue.js

Unity打包WebGL: 导入Vue,unity,webgl,vue.js
Unity打包WebGL: 导入Vue,unity,webgl,vue.js

X. 参考

  1. 与Vue结合
    【vue】vue与unity交互(不需要任何第三方插件)
    unity发布webgl平台结合vue,并实现事件交互
    vue项目接入unity3D模块并进行数据通信
    vue与unity进行交互,包括unity发收,unity自动获取数据等
    Unity3D(2021版)打包成webgl和前端vue交互

  2. JS创建和触发 events, window.top.dispatchEvent
    创建和触发 events

下载

Unity WebGL 结合 Vue的例子文章来源地址https://www.toymoban.com/news/detail-670353.html

到了这里,关于Unity打包WebGL: 导入Vue的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 基于Unity+Vue3通信交互的WebGL项目发布实践

    问题背景 我们最近需要把unity开发的pc项目迁移到web端,因为unity支持发布webgl。所以按照以往的开发流程,都是项目开发完成就发布webgl部署到服务器。 突然有一天,测试人员提出说为什么我们做的网页跟别人的不太一样呢?具体看下面两张图: 1、unity使用ugui做的界面发布

    2024年04月17日
    浏览(39)
  • Unity之webgl端通过vue3接入腾讯云联络中心SDK

    腾讯云联络中心SDK:云联络中心 Web-SDK 开发指南-文档中心-腾讯云 (tencent.com) ​  1.1 对其进行解压 ​  1.2根据文档操作 查看README.md,根据说明设置server下的dev.js里的相关参数。 然后打开电脑终端,cd到项目的路径: ​ 安装依赖   ​ 运行 ​  1.3 运行demo 复制http://127.0.0.1:5173

    2024年02月14日
    浏览(26)
  • Unity打包WebGL的优化常用操作?

    如果贴图格式时2048,在不影响画面效果的情况下,改成1024或者5#12,还可以缩小包体。 WebGL打包的时候分三种压缩情况: gzip:比Brotli文件打,但打包快,http和https都支持 Brotli:压缩格式最小,打包慢,只有谷歌和火狐支持。 Disabled:不压缩。 直接打包一份不压缩的版本,在

    2024年02月06日
    浏览(37)
  • Unity WebGL项目打包后本地打开报错问题解决方法

    在Unity打包WebGL项目后,本地打开html页面出现错误提示。 Failed to download file Build/Unity Web.data.gz. Loading web pages via a file:// URL without a web server is not supported by this browser.   在网上试了好几种方法,综合起来终于跑起来了。以下是解决步骤: 1. 打开Web服务 ,打开控制面板--程序--启

    2024年02月14日
    浏览(44)
  • Unity-WebGL基于JS实现网页录音

          因为该死的Unity不支持WebGL的麦克风,所以只能向网页借力,用网页原生的navigator.getUserMedia录音,然后传音频流给Unity进行转AudioClip播放。       还有一点非常重要:能有同事借力就直接问,厚着脸皮上,我自己闷头两天带加班,不如同事谭老哥加起来提供帮助的俩小

    2023年04月08日
    浏览(28)
  • Unity3D中打包WEBGL后读取本地文件数据+网络请求

    首先上一编博主运行html之后报的错误:提示内存不足!!!! 1.首先排查一下webgl包的大小,不能超过2G。 2.F12查看具体错误,在这里博主的是:        a:本地读取StreamingAssets里的配置文件,序列化失败。        b:网络请求方法不能使用JsonConvert.SerializeObject将对象重新序列

    2024年02月08日
    浏览(41)
  • 【虚拟仿真】Unity3D打包WEBGL后播放视频(VideoPlayer组件)

    推荐阅读 CSDN主页 GitHub开源地址 Unity3D插件分享 简书地址 我的个人博客 大家好,我是佛系工程师 ☆恬静的小魔龙☆ ,不定时更新Unity开发技巧,觉得有用记得一键三连哦。 本篇文章实现Unity3D打包WEBGL后播放视频,如下图所示: 使用了VideoPlayer组件,代码比较简单。 主要就

    2023年04月25日
    浏览(45)
  • Unity打包WebGL的全过程及在打包和使用过程中会遇到的问题

    目录 概要 Unity打包WebGL PlayerSettings设置 Resolution and Presentation Other Settings  Publishing Settings 本地服务器测试环境配置 问题盘点         盘点Unity在Build WebGL环境包时需要的配置以及遇到的难题 Resolution and Presentation Resolution and Presentation 界面主要设置打包后的WebGL界面的分辨率显

    2024年02月16日
    浏览(27)
  • unity webGL与js 交互(获取地址栏URL)

    1.unity传值给js unity中: js中: 2.js传值给unity 参数一 Cookie:场景中物体的名称 (最上层父物体名字,否则无法成功传值) 参数二 OnCookie_Callback:方法名称 参数三 result:值 unity中: 完整: unity场景中物体的名称  untiy代码: js代码:

    2024年02月04日
    浏览(44)
  • Unity减少发布打包文件的体积(二)——设置WebGL发布时每张图片的压缩方式

    一个项目在发布成WebGL后,其体积至关重要,体积太大,用户加载会经历一个漫长的等待…轻则骂娘,重则用脚把电脑踢烂(扣 质 保 金 )… 那么如何减少发布后的体积呢,本文从图片的压缩开始入手。 前传回顾: Unity减少发布打包文件的体积(一)——获取精灵图片的信息限

    2024年02月04日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包