[Unity]游戏内查看BundleVersion版本号.

22 篇文章 0 订阅
9 篇文章 0 订阅

转载自StackOverFlow

基本原理是[InitializeOnLoad]
在每次有变动完毕之后会执行BundleVersionChecker
在BundleVersionChecker中会自动判断版本号是否变更,如果变更会把新的版本号写入cs文件.
从而实现在游戏中获取版本号.

我直接贴代码吧

using System.IO;
using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
public class BundleVersionChecker
{
    /// <summary>
    /// Class name to use when referencing from code.
    /// </summary>
    private const string ClassName = "CurrentBundleVersion";

    // cs文件路径
    private const string TargetCodeFile = "Assets/GameResources/Script/Config/" + ClassName + ".cs";

    static BundleVersionChecker()
    {
        string bundleVersion = PlayerSettings.bundleVersion;
        string lastVersion = CurrentBundleVersion.version;

        if (lastVersion != bundleVersion)
        {
            Debug.Log("Found new bundle version " + bundleVersion + " replacing code from previous version " + lastVersion + " in file \"" + TargetCodeFile + "\"");
            CreateNewBuildVersionClassFile(bundleVersion);
        }
    }

    private static string CreateNewBuildVersionClassFile(string bundleVersion)
    {
        using (StreamWriter writer = new StreamWriter(TargetCodeFile, false))
        {
            try
            {
                string code = GenerateCode(bundleVersion);
                writer.WriteLine("{0}", code);
            }
            catch (System.Exception ex)
            {
                string msg = " threw:\n" + ex.ToString();
                Debug.LogError(msg);
                EditorUtility.DisplayDialog("Error when trying to regenerate class", msg, "OK");
            }
        }
        return TargetCodeFile;
    }

    /// <summary>
    /// Regenerates (and replaces) the code for ClassName with new bundle version id.
    /// </summary>
    /// <returns>
    /// Code to write to file.
    /// </returns>
    /// <param name='bundleVersion'>
    /// New bundle version.
    /// </param>
    private static string GenerateCode(string bundleVersion)
    {
        string code = "public static class " + ClassName + "\n{\n";
        code += System.String.Format("\tpublic static readonly string version = \"{0}\";", bundleVersion);
        code += "\n}\n";
        return code;
    }
}
// 另外一个文件
public static class CurrentBundleVersion
{
    public static readonly string version = "0.8.5";
}

实际调用

if (CurrentBundleVersion != "0.8.4")
{
    // do migration stuff
}
  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值