一、介绍
- 背景:
需要直接在游戏内展示一个webview视窗 - UniWebView(版本3.0+)
UniWebView 是一个 Unity 3D 插件,用于将 Web 视图组件添加到 iOS 和 Android 上的 Unity 3D 手机游戏。它在 C# 中提供了一组抽象、跨平台和高级 API。使用 UniWebView,您可以在不了解原生开发的情况下将一些行为(例如浏览器)放入您的游戏中。 当您需要显示公告或通知、为玩家排名添加排行榜或向您的用户显示任何交互式网页时,它会极大地促进您的开发过程。 官网地址 UniWebView 4.7 提取码:2jhf UniWebView 3.0+ 提取码:gd0w
二、使用
1.使用方法相对简单,直接上代码
public class UniWebPresenter :UIPresenterBase
{
[SerializeField] private RectTransform m_UniWebRectTransform;
private UniWebView m_UniWebView;
private string m_Url;
private bool m_Log;
public override void Init(params object[] parameters)
{
m_Url = parameters[0] as string;
if(string.IsNullOrEmpty(m_Url))
{
Destroy(gameObject);
}
m_Log = GameSetting.Instance.Log;
CreateUniWebView();
OnLoaded();
}
public void CreateUniWebView()
{
m_UniWebView = m_UniWebRectTransform.gameObject.AddComponent<UniWebView>();
m_UniWebView.ReferenceRectTransform = m_UniWebRectTransform;
m_UniWebView.OnMessageReceived += OnMessageReceived;
m_UniWebView.OnPageStarted += OnPageStarted;
m_UniWebView.OnPageFinished += OnPageFinished;
m_UniWebView.OnKeyCodeReceived += OnKeyCodeReceived;
m_UniWebView.OnPageErrorReceived += OnPageErrorReceived;
m_UniWebView.OnShouldClose += OnShouldClose;
m_UniWebView.SetBackButtonEnabled(true);
m_UniWebView.SetAllowFileAccessFromFileURLs(true);
m_UniWebView.SetShowSpinnerWhileLoading(true);
m_UniWebView.SetHorizontalScrollBarEnabled(false);
m_UniWebView.SetVerticalScrollBarEnabled(false);
m_UniWebView.BackgroundColor = Color.white;
}
public void OnLoaded()
{
m_UniWebView.Load(m_Url);
m_UniWebView.Show();
}
private void OnReLoaded()
{
if (m_UniWebView.isActiveAndEnabled)
{
m_UniWebView.Reload();
}
}
private void OnClose()
{
m_UniWebView.Hide();
Destroy(gameObject);
}
private void OnPageStarted(UniWebView webView, string url)
{
if(m_Log)
Debug.Log("[UbiWebPresenter] OnPageStarted " + url);
}
private void OnPageFinished(UniWebView webView, int statusCode, string url)
{
if (m_Log)
Debug.Log("[UbiWebPresenter] OnPageFinished statusCode:" + string.Format("statusCode:{0},url{1}", statusCode, url));
}
private void OnPageErrorReceived(UniWebView webView, int errorCode, string errorMessage)
{
if (errorCode == -2)
{
OnClose();
}
if (m_Log)
Debug.Log("[UbiWebPresenter] OnPageErrorReceived :" + string.Format("errorCode:{0},errorMessage{1}", errorCode, errorMessage));
}
private void OnKeyCodeReceived(UniWebView webView, int keyCode)
{
if (keyCode == 4)
{
OnClose();
}
if (m_Log)
Debug.Log("[UbiWebPresenter] OnKeyCodeReceived keycode:" + keyCode);
}
private void OnMessageReceived(UniWebView webView, UniWebViewMessage message)
{
if (m_Log)
Debug.Log("[UbiWebPresenter] OnMessageReceived :" + message.RawMessage);
}
private bool OnShouldClose(UniWebView webView)
{
webView.CleanCache();
webView = null;
return true;
}
}
三、坑
- url必须加协议前缀 http://、https://之类,否则网页打开一片空白
- 注意:UniWebView只支持Android、iOS和Mac平台,Windows是打不开的
|