基本原理是[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
}