資料參考地址:
https://blog.csdn.net/qq_37310110/article/details/79761844
https://blog.csdn.net/shen71702163/article/details/79283645
https://docs.uniwebview.com/guide/position-and-size.html#setting-frame
首先這裏提供幾個可以使用的UniWebView插件
鏈接:https://pan.baidu.com/s/1oOiUftaioXEn06-FIRTZkA
提取碼:9yao
導入之後就是這樣,還有個參考Demo
參考網上教程:(https://blog.csdn.net/qq_37310110/article/details/79761844#commentsedit)
在UniWebViewHelper裏面加個方法
public static UniWebView CreateUniWebView(GameObject go, string url, float top, float left, float bottom, float right)
{
if (go == null || !go.activeSelf)
{
return null;
}
var view = go.GetComponent<UniWebView>();
if (view == null)
{
view = go.AddComponent<UniWebView>();
}
view.insets = new UniWebViewEdgeInsets(UniWebViewHelper.ConvertPixelToPoint(top, false), UniWebViewHelper.ConvertPixelToPoint(left, true), UniWebViewHelper.ConvertPixelToPoint(bottom, false), UniWebViewHelper.ConvertPixelToPoint(right, true));
view.SetShowSpinnerWhenLoading(true);
view.immersiveMode = false;
view.url = url;
return view;
}
private static int ConvertPixelToPoint(float num, bool v)
{
#if UNITY_IOS && !UNITY_EDITOR
float scale = 0;
if(v)
{
scale = 1f * screenWidth / Screen.width;
}
else
{
scale = 1f * screenHeight / Screen.height;
}
return (int)(num*scale);
#endif
return (int)num;
}
目的在於隨時用隨時Create。而且網頁顯示界面的初始化也可以寫在裏面包括一些界面尺寸,顯示模式,目標網址
新建OpenUrl類
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class OpenURL : MonoBehaviour
{
public InputField _url;
public Button _enterBtn;
public Button _backBtn;
UniWebView _view;
private void Awake()
{
_enterBtn.onClick.AddListener(OpenUrl);
}
public void OpenUrl()
{
if (_view != null)
{
_view.CleanCache();
}
if (_url.text == null)
{
return;
}
_view = UniWebViewHelper.CreateUniWebView(gameObject, "https://" + _url.text, 100, 0, 50, 0);
_view.OnLoadComplete += View_OnLoadComplete;
_view.Load();
}
private void View_OnLoadComplete(UniWebView webView, bool success, string errorMessage)
{
if (success)
{
webView.Show();
_backBtn.gameObject.SetActive(true);
}
else
{
Debug.LogError("Something wrong in webview loading: " + errorMessage);
}
}
public void CloseUrl()
{
_view.Hide();
_view.OnLoadComplete -= View_OnLoadComplete;
Destroy(_view);
}
}
創建兩個按鈕和一個輸入框,在canvas下掛OpenURL和UniWebView這兩個腳本,記得給OpenURL掛按鈕,那個UniWebView參數直接是在代碼改變的,所以不用設置。
然後,這樣就成功了,不過注意如圖下是因爲在OpenURL腳本里的OpenUrl方法本來加了http://,可以選擇去掉或者輸入不要http://。