过时:虽然此答案在撰写本文时完全有效,但其中包含的信息已过时。现在有更好的方法可以做到这一点,请参阅this answer。由于历史原因,答案已被保留。
更新
我对下面描述的解决方案进行了大量改进,并用它制作了一个托管在 github 上的开源项目(MIT 许可证)。一目了然,它不仅提供了对当前运行应用程序捆绑版本的访问权限,而且还以一种非常方便的方式跟踪以前捆绑版本的历史记录 - 至少因为需要安装插件或进行一些手动调整。
所以看看:
BundleVersionChecker at github
Usage and more details
我刚刚找到了另一个非常方便的解决方案。需要 2 个类:
第一个是检查当前PlayerSettings.bundleVersion 的编辑器类。我称它为BundleVersionChecker,它必须放在资产/编辑器中。它用作代码生成器,如果捆绑版本已更改,则仅生成一个非常简单的静态类,其中仅包含版本字符串:
using UnityEngine;
using UnityEditor;
using System.IO;
[InitializeOnLoad]
public class BundleVersionChecker
{
/// <summary>
/// Class name to use when referencing from code.
/// </summary>
const string ClassName = "CurrentBundleVersion";
const string TargetCodeFile = "Assets/Scripts/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);
}
}
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>
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;
}
}
第二类称为CurrentBundleVersion。它是上面提到的由BundleVersionChecker 生成的简单类,它可以从您的代码中访问。
只要它的版本字符串不等于在PlayerSettings 中找到的字符串,它就会由BundleVersionChecker 自动重新生成。
public static class CurrentBundleVersion
{
public static readonly string version = "0.8.5";
}
因为它是生成的代码,您不必关心它,只需将其提交到您的版本控制系统中即可。
所以你可以在代码中的任何地方编写:
if (CurrentBundleVersion != "0.8.4") {
// do migration stuff
}
我目前正在开发一个更复杂的版本。这将包含一些版本跟踪来执行类似
的操作
if (CurrentBundleVersion.OlderThan (CurrentBundleVersion.Version_0_8_5) //...