赞
踩
在各类3D大屏的应用中,播放流媒体(例如监控视频)是比较常见的需求,本文会提供以内嵌浏览器的方案来解决该需求。
首先,功能基于插件3D WebView-Windows-macOS-Web Browser v4.2(官方下载地址:3D WebView: the ultimate cross-platform web browser for Unity | Vuplex Store)
文章提供的干货。
代码如下
HTML:
- <body>
- <div>
- <button onclick="sendMessageToCSharp()">网页向Unity发消息</button>
- </div>
- <div id="mapDiv" style="position: absolute; width: 100vw; height: 100vh"></div>
- <script>
- //Unity向网页发消息
- if (window.vuplex) {
- addMessageListener();
- } else {
- window.addEventListener('vuplexready', addMessageListener);
- }
- function addMessageListener() {
- window.vuplex.addEventListener('message', function (event) {
- let json = event.data;
- // > JSON received: { "type": "greeting", "message": "Hello from C#!" }
- // alert('JSON received: ' + json);
- json = JSON.parse(json)
- DrawLine(json.data);
- });
- }
-
-
- //网页向Unity发消息
- if (window.vuplex) {
- sendMessageToCSharp();
- } else {
- window.addEventListener('vuplexready', sendMessageToCSharp);
- }
- function sendMessageToCSharp() {
- console.log("发送消息到Unity");
- window.vuplex.postMessage({ type: 'greeting', message: 'Hello from JavaScript!' });
- }
- </script>
- </body>
C#:
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using Vuplex.WebView;
-
- [HelpURL("https://blog.csdn.net/qq_41973169/article/details/129179855")]
- public class Demo : MonoBehaviour
- {
- public CanvasWebViewPrefab canvasWebView;
- // Start is called before the first frame update
- async void Start()
- {
- if (!canvasWebView) canvasWebView = GetComponent<CanvasWebViewPrefab>();
-
- await canvasWebView.WaitUntilInitialized();
-
- canvasWebView.WebView.LoadUrl("http://127.0.0.1:5500/%E8%BD%A6%E8%BE%86%E8%B7%AF%E7%BA%BF.html");
- await canvasWebView.WaitUntilInitialized();
- await canvasWebView.WebView.WaitForNextPageLoadToFinish();
- //var headerText = await canvasWebView.WebView.ExecuteJavaScript("alert('111111')");
- Debug.Log("Unity执行页面JS.");
-
-
- Send a message after the page has loaded.
- //await canvasWebView.WebView.WaitForNextPageLoadToFinish();
- canvasWebView.WebView.PostMessage("{\"type\": \"greeting\", \"message\": \"http://http://127.0.0.1:5500/rtp/bfe3ecb51e4ff5166554e.live.flv\"}");
-
- canvasWebView.WebView.MessageEmitted += MessageEmittedCallback;
- }
-
- private void MessageEmittedCallback(object sender, EventArgs<string> e)
- {
- Debug.LogWarning("JSON received: " + e.Value);
- }
- }
最后视频运行效果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。