Unity 启动时版本比较弹窗提示和强制退出:完整示例

问题: 想让 Unity 在启动时进行版本比较,如果版本不匹配,则显示弹窗提示,并提供强制退出按钮。此外,Unity 提示 www.isNetworkError || www.isHttpError 已被弃用,需要找到替代方案。

解决方案: 以下示例代码展示了如何实现版本比较、弹窗提示和强制退出,并解决了 www.isNetworkError || www.isHttpError 弃用问题。

步骤:

  1. 创建版本检查脚本 (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
    }
}
  1. 创建弹窗管理脚本 (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);
    }
}
  1. 创建 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 中运行游戏时,它将检查远程版本文件,并将根据版本比较结果显示弹窗提示,并在版本不匹配时提供强制退出按钮。

Unity 启动时版本比较弹窗提示和强制退出:完整示例

原文地址: https://www.cveoy.top/t/topic/cnK1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录