ゲーム中にバンドルバージョンを表示する
バグ報告を受けたときに「えっ、それどのバージョンのロムで発生したの?」って聞きたいときにタイトル画面などでバンドルバージョンを表示するようにしておくと便利だったりします。
バンドルバージョン自体はUnityEditor.PlayerSettings.bundleVersionで取得できるのですが、厄介なのは、これはUnityEditorで動かしている時以外は取得できないことです。
じゃあ、UnityEditor以外でバンドルバージョンを知るために、一旦ファイルに書き出しておこう!っていう発想になったりします。
Unityの中の人に質問したら、Stack Over Flowに、同様のことを質問しているのがありましたよーって教えてくれました。
これです↓
stackoverflow.com
実装説明
まず、最初にCurrentBundleVersion.csというファイルを作っておきます。
中身は、こんな感じです。
public static class CurrentBundleVersion { public static readonly string version = "0.0"; }
次に、BundleVersionChecker.csという名前の以下のようなスクリプトをEditorフォルダ以下に置いておきます。
using UnityEngine; using UnityEditor; using System.IO; [InitializeOnLoad] public class BundleVersionChecker { const string ClassName = "CurrentBundleVersion"; const string TargetCodeFile = "Assets/" + ClassName + ".cs"; static BundleVersionChecker () { string bundle_version = PlayerSettings.bundleVersion; string last_version = CurrentBundleVersion.version; if (last_version != bundle_version) { Debug.Log ("バージョンが新しくなりました!" + TargetCodeFile + "内に書かれたバージョンを" + last_version +"から" + bundle_version + "に変えます。" ); CreateNewBuildVersionClassFile (bundle_version); } } static string CreateNewBuildVersionClassFile (string bundle_version) { using (StreamWriter writer = new StreamWriter (TargetCodeFile, false)) { try { string code = GenerateCode (bundle_version); writer.WriteLine ("{0}", code); } catch (System.Exception ex) { string msg = " threw:\n" + ex.ToString (); Debug.LogError (msg); EditorUtility.DisplayDialog ("Error クラスを作りなおし中にエラーが発生しました!", msg, "OK"); } } return TargetCodeFile; } static string GenerateCode (string bundle_version) { string code = "public static class " + ClassName + "\n{\n"; code += System.String.Format ("\tpublic static readonly string version = \"{0}\";", bundle_version); code += "\n}\n"; return code; } }
このBundleVersionChecker.csのstaticコンストラクタが起動すると、CurrentBundleVersion.cs内のversionを書き換わります。
BundleVersionChecker.csはEditorフォルダ以下に置かれているので、コンパイルが走るタイミングでスタティックコンストラクタが呼ばれて書き換えてくれます。
サンプルプロジェクトをgithubに置いておきます。
github.com
起動するとバージョンが表示されて、しばらくするとフェードアウトするようになっています。