Unity3D UniWebView 入门教程

Unity3D UniWebView 入门教程

UniWebView 是 Unity3D 环境下的 webview 组件,能方便的让 unity 结合网页实现 hybrid app 原生+web 的混合开发。


Controller.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Controller : MonoBehaviour {

    UniWebView webView;

    // Use this for initialization
    void Start () {
        // Create a game object to hold UniWebView and add component.
        var webViewGameObject = new GameObject("UniWebView");
        webView = webViewGameObject.AddComponent<UniWebView>();

        
        webView.Frame = new Rect(0, 0, Screen.width, Screen.height);
        webView.Show();
webView.Load("http://docs.uniwebview.com/game.html");
} // Update is called once per frame void Update () { } }


 webView.Show();  显示
 webView.hide();    隐藏
webView.OnPageFinished 监听html页面加载完成
webView.EvaluateJavaScript() 执行javascript脚本


UniWebView 的一些属性
bool CanGoBack { get; }      是否可以后退,对于unity自己维护导航界面的前进后退,这个就很重要了。
bool CanGoForward { get; } 是否可以前进


关于网页加载慢的问题,好像先显示 webview,再加载,体验会好一点。
webView.Show();
webView.Load("http://docs.uniwebview.com/game.html");


先load() 再show() 似乎要慢一些,
他的过程似乎是这样的:等待html载入,等待网页图片、css样式、js脚本加载完成,全部完成最后才显示。
先 show() 再 load() ,就是等着html载入,用户就逐渐就能看到网页界面的内容了。不用等那么久。
还有个属性可以控制这个行为:
autoShowWhenLoadComplete = true
作用:
If true, show the webview automatically when it finished loading.


UniWebview 似乎没有 DOMContentLoaded 的对应的 event 回调事件、钩子。也是烦人。
如果有对应的钩子,原生层的loading转圈,然后在 DOMContentLoaded 之后,html 页面自带一个loading、内容展示,网页的内容展现需要的时长就短一些。
比从webview实例化到网页所有资源加载后再展示,要快得多。


加载本地 html 文件
void LoadHTMLString(string htmlString, string baseUrl, bool skipEncoding)
Load an HTML string in current web view.
这个可以加载(或者叫装载)本地html file 文件。


UniWebview API 文档

UniWebview  v3.x 的文档

用代码的方式接入 uni webview:


UniWebview v2.x 的文档



UniWebView 不是 iOS 的UIwebview。
但是在 iOS 平台,UniWebView 对应的底层,也就是 UIwebview、WKwebview这些东西了。