NLDClient-yudde/ProjectNLD/Assets/Code/Scripts/GameWrapper/WebController.cs

75 lines
1.9 KiB
C#
Raw Normal View History

2025-04-28 10:56:57 +08:00
using UnityEngine;
// Test
public class WebController : MonoBehaviour
{
UniWebView webView;
2025-04-28 10:56:57 +08:00
void Start()
{
2025-04-28 10:56:57 +08:00
DontDestroyOnLoad(this);
// Create a game object to hold UniWebView and add component.
var webViewGameObject = new GameObject("UniWebView");
webView = webViewGameObject.AddComponent<UniWebView>();
DontDestroyOnLoad(webViewGameObject);
webView.Frame = new Rect(0, 0, 2000, 4000);
webView.Load("https://docs.uniwebview.com/game.html");
webView.Show();
webView.OnPageFinished += (view, statusCode, url) =>
{
DebugUtil.LogError("关闭网页");
webView.EvaluateJavaScript("startGame();", (payload) =>
{
if (payload.resultCode.Equals("0"))
{
Debug.Log("Game Started!");
}
else
{
Debug.Log("Something goes wrong: " + payload.data);
}
});
};
webView.OnShouldClose += (view) =>
{
DebugUtil.LogError("清理网页");
webView = null;
return true;
};
webView.OnMessageReceived += (view, message) =>
{
if (message.Path.Equals("game-over"))
{
var score = message.Args["score"];
DebugUtil.LogError("Your final score is: " + score);
webView.EvaluateJavaScript($"getStars({score})",
(payload) => { DebugUtil.LogError("Stars: " + payload.data); });
Invoke(nameof(Restart), 3.0f);
}
if (message.Path.Equals("close"))
{
Destroy(webView);
webView = null;
}
};
2025-04-28 10:56:57 +08:00
}
void Restart()
{
if (webView != null)
2025-04-28 10:56:57 +08:00
{
webView.Reload();
}
2025-04-28 10:56:57 +08:00
}
void Update()
{
}
2024-12-19 19:05:05 +08:00
}