Unity 内嵌前端网页与通信 (zfbrower、3dwebview)

前端 0

Unity 内嵌网页通信

插件:3dwebview
需要添加的组件和一些canvas的设置,可参考插件提供的示例场景。
加载网页、 前端到Unity,Unity到前端的参数互传使用方法:
前端

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <!--设置透明页面-->    <meta name='transparent' content='true'>    <meta name="theme-color" content="#000000">    <title>Document</title></head><body>    <div width>        <button type="button" onclick="sendMessageToCSharp()">            给Unity传参        </button>    </div>    <script>   if (window.vuplex) {            addMessageListener();        } else {            window.addEventListener('vuplexready', addMessageListener);        }		<!-- 接收参数 -->        function addMessageListener() {            window.vuplex.addEventListener('message', function (event) {                let json = event.data;                console.log('JSON received: ' + json);            });        }		<!-- 发送参数 -->        function sendMessageToCSharp() {            window.vuplex.postMessage({ type: 'greeting', message: 'Hello from JavaScript!' });        }    </script></body></html>

C#

	//webview的获取 	private CanvasWebViewPrefab webViewPrefab; 	//要加载的网页,本地网页 或 url都行    private string urlPath;    public void Awake()    {        urlPath = Application.streamingAssetsPath + "/Url.json";    }    async void Start()    {        webViewPrefab = GetComponent<CanvasWebViewPrefab>();        if (File.Exists(urlPath))        {            string jsonData = File.ReadAllText(urlPath);            //加载网页url            webViewPrefab.InitialUrl = jsonData;        }        //等待加载        await webViewPrefab.WaitUntilInitialized();        //使用背景透明        webViewPrefab.WebView.SetDefaultBackgroundEnabled(false);        //从前端传参数到Untiy        webViewPrefab.WebView.MessageEmitted += (sender, eventArgs) =>        {            Debug.Log("(C#Log)JSON received: " + eventArgs.Value);        };        await webViewPrefab.WebView.WaitForNextPageLoadToFinish();    }    //从Unity 传参数到 前端    public void PostMessageToJS()    {        string time = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");        string PostContent = "{/"type/": /"Time/", /"message/": /"" + time + "/"}";        webViewPrefab.WebView.PostMessage(PostContent);    }

关于这个接收的参数的处理,直接字符串处理就行。
如果分辨率过大,导致渲染出错,加一下宏定义就可以了
在这里插入图片描述

注意,这地方有个坑,就是透明网页,在前端设置的透明,如果网页像素超过3dwebview推荐的分辨率,会导致无法透明,要在C#里写 webViewPrefab.WebView.SetDefaultBackgroundEnabled(false); 但是这个SetDefaultBackgroundEnabled的API ,旧版本没有,这里使用的是4.3.2,这个版本是有的。
优点:
1:可以播放网页视频。打开下图所示,就可以了。
在这里插入图片描述

2: 3dwebview有不同的平台的版本,找到对应版本就行。
这里提供windwos的4.3.2的版本
https://download.csdn.net/download/weixin_44347839/88616800?spm=1001.2014.3001.5503
缺点:不能实现透过网页点击的功能

插件:zfbrower(Embedded Browser)
需要添加的组件和一些canvas的设置,可参考插件提供的示例场景。
如果你发现你的示例场景跑不起来,把里面的DemoBrowserAssets.zip 解压到assets的同级目录。
加载网页、 前端到Unity,Unity到前端的参数互传使用方法:
前端

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Document</title></head><body>	    <button type="button" onclick="jsevent()">给Unity传参</button>      <script type="text/javascript">       //接收Unity的参数        function receivedFromUnity(item) {				 console.log("Unity传参:"+item);		}    </script></body></html>

c#

  	private Browser browser;  	private string urlPath;  	public void Awake()    {        urlPath = Application.streamingAssetsPath + "/Url.json";    }    void Start()    {    	// 获取brower        browser = GetComponent<Browser>();       	//要加载的网页,本地网页 或 url都行       	if (File.Exists(urlPath))        {            string jsonData = File.ReadAllText(urlPath);            //加载网页url            browser.LoadURL(jsonData,true);        }         //从前端传参数到Untiy       	  browser.RegisterFunction("jsevent", (JSONNode jv) =>        {            Debug.Log(jv[0].Value);        });    }    int t=0;  	 void Update()    {         //从Unity 传参数到 前端        if (Input.GetKeyDown(KeyCode.S))        {            t++;            browser.CallFunction("receivedFromUnity", t).Done();            //  browser.CallFunction("alert('unitytoweb')").Done();        }    }

优点:
能实现透过网页点击的功能,取消勾选即可。
在这里插入图片描述
想要在网页输入中文,在PointerUIGUI.cs中,有个OnSelect方法,把IMECompositionMode 改成true。
如果提示加载的连接不是私密连接,在BrowerNative.cs中有个list,commandLineSwitches,添加"–ignore-certificate-errors"。
缺点:
1:不可以播放网页视频。(ws,flv除外)
2: 只支持PC
这里提供3.1.0的版本
https://download.csdn.net/download/weixin_44347839/88616802?spm=1001.2014.3001.5503

也许您对下面的内容还感兴趣: