Unity 启动时版本比较弹窗提示和强制退出:完整示例
Unity 启动时版本比较弹窗提示和强制退出:完整示例
问题: 想让 Unity 在启动时进行版本比较,如果版本不匹配,则显示弹窗提示,并提供强制退出按钮。此外,Unity 提示 www.isNetworkError || www.isHttpError 已被弃用,需要找到替代方案。
解决方案: 以下示例代码展示了如何实现版本比较、弹窗提示和强制退出,并解决了 www.isNetworkError || www.isHttpError 弃用问题。
步骤:
- 创建版本检查脚本 (VersionChecker.cs):
using UnityEngine;
using UnityEngine.UI;
public class VersionChecker : MonoBehaviour
{
public string updateUrl = "https://3dlingyu.com/update.txt";
public string currentVersion = "1.3";
public DialogManager dialogManager;
private void Start()
{
StartCoroutine(CheckVersion());
}
private IEnumerator CheckVersion()
{
using (var www = UnityWebRequest.Get(updateUrl))
{
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError("版本比较失败:" + www.error);
yield break;
}
string remoteVersion = www.downloadHandler.text.Trim();
if (remoteVersion != currentVersion)
{
string message = "当前版本:" + currentVersion + "\n最新版本:" + remoteVersion;
dialogManager.ShowDialog("版本不匹配", message, "退出", QuitGame);
}
}
}
private void QuitGame()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
- 创建弹窗管理脚本 (DialogManager.cs):
using UnityEngine;
using UnityEngine.UI;
public class DialogManager : MonoBehaviour
{
public GameObject dialogPanel;
public Text titleLabel;
public Text messageLabel;
public Button closeButton;
public void ShowDialog(string title, string message, string buttonText, UnityEngine.Events.UnityAction buttonAction)
{
titleLabel.text = title;
messageLabel.text = message;
closeButton.onClick.RemoveAllListeners();
closeButton.onClick.AddListener(buttonAction);
dialogPanel.SetActive(true);
}
}
-
创建 UI 画布和关联:
- 创建一个 UI 画布 (Canvas)。
- 将
DialogManager脚本附加到画布上。 - 在画布上创建一个面板 (Panel) 作为弹窗。
- 为面板添加子对象:
Text组件作为标题标签 (titleLabel) 和消息标签 (messageLabel),以及Button组件作为关闭按钮 (closeButton)。 - 在
DialogManager脚本中将这些 UI 元素分配给相应的属性。
代码说明:
-
VersionChecker.cs:
updateUrl:远程版本文件的 URL。currentVersion:当前版本号。dialogManager:引用DialogManager脚本实例。Start():在场景启动时开始检查版本。CheckVersion():使用UnityWebRequest获取远程版本文件内容并进行版本比较。QuitGame():强制退出游戏,根据平台调用不同的方法。
-
DialogManager.cs:
dialogPanel:弹窗面板对象。titleLabel、messageLabel、closeButton:弹窗内的 UI 元素。ShowDialog():显示弹窗并设置标题、消息和按钮文本。
注意:
www.isNetworkError || www.isHttpError已被弃用,使用UnityWebRequest.Result检查请求结果。www.text已被替换为www.downloadHandler.text。
运行结果:
当你在 Unity 中运行游戏时,它将检查远程版本文件,并将根据版本比较结果显示弹窗提示,并在版本不匹配时提供强制退出按钮。
原文地址: https://www.cveoy.top/t/topic/cnK1 著作权归作者所有。请勿转载和采集!