Unity UniWebView内嵌浏览器插件使用教程

最近做项目的时候使用到了内嵌浏览器,使用到了UniWebView插件。在Windows平台的时候是无法看到效果的需要打包出来才可以看到的哦

插件下载链接:点击进入下载链接

使用的时候遇到了很多坑,最后还是做好了,写篇文章记录一下使用方法。

private static UniWebView uniWebView;
    private static GameObject webobj;

    private static string webUrl = string.Empty;
    private static Vector4 Insets;

    /// <summary>
    /// 显示网页
    /// </summary>
    /// <param name="url">网页路径</param>
    /// <param name="is_canclose">是否可以退出掉</param>
    /// <param name="top">距离顶部的距离</param>
    /// <param name="left">距离左边的距离</param>
    /// <param name="bottom">距离下面的距离</param>
    /// <param name="right">距离右边的距离</param>
    public  void ShowWebURL(string url, bool is_canclose = false, int top = 0, int left = 0, int bottom = 0, int right = 0,float time = 0.3f)
    {
        
        StartCoroutine(Instance.StartShowWebURL(url, is_canclose, top, left, bottom, right, time));
    }

    private IEnumerator StartShowWebURL(string url, bool is_canclose, int top, int left, int bottom, int right, float time) {

        CloseWeb();

        yield return new WaitForSeconds(time);  //让上一步和下一步有所间隔

        if (webobj == null)
            webobj = new GameObject();

        uniWebView = webobj.AddComponent<UniWebView>();

        uniWebView.toolBarShow = true;
        uniWebView.autoShowWhenLoadComplete = true;
        uniWebView.SetShowSpinnerWhenLoading(false);        //关闭loging功能
        uniWebView.SetSpinnerLabelText("");                 
        if (!is_canclose)
            uniWebView.OnWebViewShouldClose += WebCloseEvent;
        uniWebView.url = url;
        webUrl = url;
        Insets.x = top;
        Insets.y = left;
        Insets.z = bottom;
        Insets.w = right;
        uniWebView.insets = new UniWebViewEdgeInsets(top, left, bottom, right);
        uniWebView.Show();
        uniWebView.Load();

    }

    /// <summary>
    /// 关闭网页
    /// </summary>
    public static void CloseWeb()
    {
        webUrl = string.Empty;
        try
        {
            if (uniWebView != null)
            {
                uniWebView.Hide();
                Destroy(uniWebView);
            }
        }
        catch{

        }
    }

 如果不添加CloseWeb 的监听的话在网页的第一个页面点击手机的返回键会将网页退出掉,添加上去之后可以在合适的时机让其返回True就可以退出网页也可以用CloseWeb函数关闭网页。

以上写完之后又发现一个bug如果有显示自己的UI的话在前后台切换的时候会出现变黑的问题,为了解决这个问题代码如下

  private void OnApplicationPause(bool focus)
    {
        if (focus)   //进入
        {
            if (!string.IsNullOrEmpty(webUrl))
            {
                ShowWebURL(webUrl, false, (int)Insets.x, (int)Insets.y, (int)Insets.z, (int)Insets.w);
            }
        }
        else {      //离开
            if (uniWebView != null)
            {
                uniWebView.Hide();
                Destroy(uniWebView);
            }
        }
    }

在每次打开网页的时候都有使用webUrl和Insets 记录最后一次打开的网址和大小,在非前后台切换的时候关闭网页做了置空操作所以当在focus为True的时候就可以进行再次打开网页。退出的时候关闭掉网页。

猜你喜欢

转载自blog.csdn.net/qq_39342142/article/details/81565558
今日推荐